组件是可复用的 Vue 实例,与 new Vue
接收相同的选项,例如 data
、computed
、watch
、methods
以及生命周期钩子等。仅有的例外是像 el
这样根实例特有的选项。
组件的创建方式一
var myComponent=Vue.extend({
template:'<h2>hello</h2>'
});
Vue.component('hello',myComponent);
组件的创建方式二
Vue.component('world',{
template:'<h2>world</h2>'
});
局部组件,注意局部组件是components,外部是component
var vm=null;
window.onload=function () {
vm=new Vue({
el:'#my',
data:{
name:'moris',
age:22,
user:{
id:100,
name:''
}
},
methods:{
changeUser(){
this.user.name='xxxx';
}
},
components: { //局部组件,注意局部组件是components,外部是component
'my-address': {
template: '#myaddress',
data(){
return{
address:'shenzhen',
arr:['龙华','坂田','龙岗']
}
}
}
}
})
}
<template id="myaddress">
<div>
<h2>{{address}}</h2> //这里取的是return返回的内容
<ul>
<li v-for="item in arr">{{item}}</li>
</ul>
</div>
</template>
可以将组件进行任意次数的复用
<div id="my">
<hello></hello>
<world></world>
<my-address></my-address>
<my-address></my-address>
</div>