new Vue()
就可以认为是一个大组件,但多个实例这样太low了,Vue为我们提供了Component
。
1.全局注册的组件
要注册一个全局组件,你可以使用 Vue.component(tagName, options)
,例如:
//注册
Vue.component('my-component', {
template: '<div>一个自定义的组件</div>'
});
//创建根实例
var vm = new Vue({
el:'#box',
});
注册一定要在实例化之前。
然后就可以在模板上使用名为my-component
的这个组件了:
<div id="box">
<my-component></my-component>
</div>
同样可以有data
,但组件里的data
是一个函数,该函数返回一个对象:
Vue.component('my-component', {
template: '<div>{{msg}}</div>',
data:function(){
return {msg:'我的标题'}
}
});
组件中的事件,还是照样写:
Vue.component('my-component', {
template: '<div @click="change">{{msg}}</div>',
data:function(){
return {msg:'我的标题'}
},
methods:{
change(){
alert(1)
}
}
});
2.局部注册
//定义组件
var child = {
template: '<div @click="change">{{msg}}</div>',
data:function(){
return {msg:'我的标题'}
},
methods:{
change(){
alert(1)
}
}
};
//创建根实例
var vm = new Vue({
el:'#box',
components:{
'my-component':child
}
});
所谓“局部组件”就是放的一个组件的里面,这里Vue的实例其实就是一个大组件。
先定义好组件,然后在Vue实例化的时候传入。