Vue元件基礎
阿新 • • 發佈:2019-01-02
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例項化的時候傳入。