注冊(cè)一個(gè)組件
有兩種方式可以注冊(cè)一個(gè)組件,第一種是全局注冊(cè),第二種是局部注冊(cè)
# 全局注冊(cè)Vue.component('my-component',{ template: '<span>Hello</span>'})# 局部注冊(cè)var child = { template: '<span>Hello</span>'}new Vue({ // ··· components:{ my-component: child }})注意:組件的注冊(cè)必須要在Vue實(shí)例創(chuàng)建之前
使用組件
<div id="app"> <my-component></my-component></div>
當(dāng)我們需要使用到data時(shí),data必須是一個(gè)函數(shù),否則將會(huì)報(bào)錯(cuò),這是Vue的一個(gè)規(guī)則,如下
Vue.component('my-component',{ template: '<span>{{message}}</span>', data:function(){ return {message:'hello'} }})組件間消息傳遞
當(dāng)我們封裝了組件A,但是組件A又嵌套了組件B,這時(shí)候組件AB形成了父子組件的關(guān)系,我們應(yīng)該怎么來讓父組件傳遞消息給子組件呢,這里用到了一個(gè)屬性值props,如下
Vue.component('my-component',{ props: ['message'] template: '<span>{{message}}</span>'})# 通過props傳遞消息給子組件<my-component message="Hello"></my-component>上面的例子,我們通過props傳遞了參數(shù)給子組件,確實(shí)能改變子組件的值,但是,假如我們有這樣一個(gè)要求,props的值是動(dòng)態(tài)改變的,那么這種靜態(tài)字面量傳遞參數(shù)的方式就不能滿足我們的需求了。如下將說明如何進(jìn)行動(dòng)態(tài)的props值設(shè)定
<div id="app"> <input v-model="parentMsg"><br> <my-component v-bind:message="parentMsg"></div>
這里通過v-bind的命令,將我們的message與parentMsg進(jìn)行綁定,這樣,當(dāng)我們的parentMsg改變時(shí),message將能實(shí)時(shí)改變
自定義事件
父子組件之間如果通過props來傳遞數(shù)據(jù)的話,那么似乎只能進(jìn)行單向的數(shù)據(jù)傳遞,只能從父組件向子組件傳遞,假如我們需要從子組件傳遞消息回去,那么就需要用到自定義事件了
# 使用v-on綁定自定義事件Vue.component('my-component',{ template: '<button v-on:click="increment">{{counter}}</button>', data: function(){ return {counter: 0} }, methods: { increment: function(){ this.counter += 1; this.$emit(increment); } }})new Vue({ el: '#app', data: { // ··· total:0 }, methods: { // ··· incrementTotal: function(){ this.total += 1; } }})<div id="app"> // ··· <p>{{total}}</p> <my-component v-on:increment="incrementTotal"></my-component></div>這里,我們點(diǎn)擊按鈕,按鈕的顯示的數(shù)值將會(huì)改變,同時(shí),total的值也會(huì)動(dòng)態(tài)的改變,這就是子組件回傳數(shù)據(jù)的實(shí)例,我們點(diǎn)擊按鈕時(shí),將會(huì)首先執(zhí)行button的onclick方法,在onclick方法里面,通過this.$emit('increment')來執(zhí)行我們自定義的事件,假如我們需要在$emit中添加參數(shù),那么我們就要在$on()中進(jìn)行回調(diào)的處理
新聞熱點(diǎn)
疑難解答
圖片精選