vue.js借鑒了angluar.js關(guān)于組件的內(nèi)容,同時增加自己的新特性,而且組件注冊非常靈活多變;支持單文件的方式,使組件開發(fā)更為清新明了。
使用組件
1,注冊
vue.js提供一系列的方法創(chuàng)建和注冊組件,這些方法包括:Vue.extend,Vue.component
//組件創(chuàng)建和注冊
var myComponent=Vue.extend({
//選項對象options,這里聲明組件包含的東西
})
Vue.component("my-component",mycomponent);
//注意單獨(dú)使用這種用法,組件是全局注冊的
組件注冊后,可以以自定義元素my-component的方式寫在父組件的模板中,同時要確保在根實(shí)例化之前注冊了組件
2,局部注冊
在不需要全局注冊組件時,使用components選項將組件注冊到另一組件內(nèi)部。
var childComponent=Vue.extend({
//選項對象
})
var parentComponent=Vue.extend({
template:"...",
components:{"my-component":childComponent}
})
3,注冊語法糖
可以直接傳遞選項對象給Vue.component和components
//注冊組件
Vue.component("my-component",{
template:"<div>注冊語法糖下注冊組件</div>"
})
//局部注冊的語法糖
var parent=Vue.extend({
components:{
"my-component":{
data:{msg:"hello vue.js"},
template:"<div>局部注冊語法糖</div>"
}
}
})
組件選項問題
特殊的選項:data和el,直接使用時,所有實(shí)例將共享這兩個選項,此時可以將這兩個選項注冊為方法
var myComponent=Vue.extend({
data:function(){
return{a:1}
}
})