全局组件的注册语法
Vue.component(组件名称, {
data: 组件数据,
template: 组件模板内容,
methods: 用户自定义方法
})
简单案例演示
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>组件的基本使用</title>
</head>
<body>
<div id="app">
<button-counter></button-counter>
<button-counter></button-counter>
</div>
<script src="js/vue.js"></script>
<script>
// 组件注册
Vue.component('button-counter', {
data: function() {
return {
count: 0
}
},
template: '<button @click="handle">+{{count}}</button>',
methods: {
handle: function() {
this.count++;
}
}
});
//创建Vue实例,得到 ViewModel
var vm = new Vue({
el: '#app',
data: {},
methods: {}
});
</script>
</body>
</html>
组件是可以重用的,并且它们当中的数据(比如案例中的count
)都是独立的
组件注册的注意事项
-
① data必须是一个函数
函数必须返回一个值
-
② 组件模板的内容必须是单个的根元素
如果存在两个
button
,它们是兄弟关系,那么就会报错,因为存在两个根元素;如果两个button
在div
里面的话,就不会报错,因为div
为一个根元素,两个button
含在div
里 -
③ 组件模板内容可以是模板字符串
-
模板字符串需要浏览器提供支持(ES6语法)
template: ` <div> <button @click="handle">+{{count}}</button><button @click="handle">+{{count}}</button> </div> `,
-
-
④ 组件命名方式
-
短横线方式
Vue.component('my-component', {})
-
驼峰方式
Vue.component('MyComponent', {})
-
注意事项
使用驼峰方式命名,如果放在其他组件的模板里使用,则可以使用
<MyComponent></MyComponent>
这种驼峰命名的方式去使用,如果放在body
里使用,则使用<my-component></my-component>
这种短横线命名的方式去使用
-
局部组件注册
vue代码
<script>
var HelloWorld = {
data: function() {
return {
msg: 'hello world'
}
},
template: '<div>{{msg}}</div>'
};
var HelloEveryone = {
data: function() {
return {
msg: 'hello everyone'
}
},
template: '<div>{{msg}}</div>'
};
var HelloChina = {
data: function() {
return {
msg: 'hello China'
}
},
template: '<div>{{msg}}</div>'
};
var vm = new Vue({
el: '#app',
data: {},
methods: {},
components: {
'hello-world': HelloWorld,
'hello-everyone': HelloEveryone,
'hello-china': HelloChina,
}
});
</script>
html代码
<div id="app">
<hello-world></hello-world>
<hello-everyone></hello-everyone>
<hello-china></hello-china>
</div>
局部组件注册,只能在父组件中使用