vue.js父子組件通信:1咏窿,父組件向子組件傳遞數(shù)據(jù)硝枉,通過(guò)props,注意數(shù)據(jù)綁定是單向的(借鑒了react);2,子組件向父組件傳遞數(shù)據(jù)较幌,通過(guò)在子組件自定義事件,使用this.$dispatch()觸發(fā)自定義事件白翻,事件冒泡到父組件乍炉,同時(shí)在父組件內(nèi)通過(guò)events或者methods,聲明回調(diào)函數(shù)滤馍,同時(shí)通過(guò)this.$dispatch()傳遞的參數(shù)將傳給父組件在events和methods中的會(huì)調(diào)函數(shù)岛琼,此時(shí)可以在回調(diào)函數(shù)中操作參數(shù)。
1巢株,父組件向子組件傳遞數(shù)據(jù)
<div id="prop">
<input v-model="parentMSG">
<child :my-message="parentMSG"></child>
</div>
//props傳遞父組件數(shù)據(jù),默認(rèn)為單向綁定槐瑞,注意:字面量語(yǔ)法傳遞的是字符串,如需要傳遞實(shí)際數(shù)值阁苞,需使用動(dòng)態(tài)語(yǔ)法v-bind:或縮寫(xiě)模式:(也即可以看成是表達(dá)式的方式),支持修飾符.sync和.once綁定修飾符困檩,綁定動(dòng)態(tài)props,注意使用駝峰形式的props時(shí)那槽,需要轉(zhuǎn)換為短橫杠的形式
Vue.component("child",{
props:{
myMessage:{
type:String,
required:true,
coerce:function(str){
return str.slice(2);
}
}
},
template:"<span>{{myMessage}}</span>"
});
var propVM=new Vue({
el:"#prop",
data:{
parentMSG:""
}
})
//此例中我們通過(guò)v-model將input中的數(shù)據(jù)綁定到父組件模板中悼沿,此時(shí)input和父組件數(shù)據(jù)是雙向綁定,input數(shù)據(jù)傳遞給在子組件中定義的props,再將props傳遞給子組件中的span子元素骚灸,實(shí)時(shí)更新
2糟趾,子組件向父組件傳遞數(shù)據(jù)
<template id="child-template">
<input v-model="msg">
<button v-on:click="notify" >觸發(fā)自定義事件</button>
{{childmsg}}
</template>
<div id="events-example">
<p>Message:{{messages|json}}</p>
//通過(guò)methods方法時(shí),注意需要在父組件模板中的子組件上綁定事件
<child v-on:child-msg="handleIt"></child>
//通過(guò)events方法時(shí),只需在父組件的選項(xiàng)對(duì)象中events拉讯,寫(xiě)入child-msg方法
//我們還可以在父組件事件監(jiān)聽(tīng)回調(diào)中涤浇,通過(guò)props將數(shù)據(jù)傳回個(gè)子組件
<child :childmsg="messages"></child>
</div>
Vue.component("child",{
template:"#child-template",
data:function(){
return {msg:"hello"};
},
methods:{
//這里是button按鈕點(diǎn)擊后的事件處理函數(shù)
notify:function(){
if(this.msg.trim()){
//在這里我們綁定了一個(gè)子定義的事件child-msg,同時(shí)傳入一個(gè)參數(shù),此參數(shù)可以傳遞給父組件的事件回掉函數(shù)
this.$dispatch("child-msg",this.msg);
this.msg="";
}
}
}
});
var eventParent=new Vue({
el:"#events-example",
data:{
messages:[]
},
props:{parentprop:""},
//我們可以在這里注冊(cè)子組件自定義事件監(jiān)聽(tīng)回調(diào)
methods:{
// handleIt:function(msg){
// console.log("子組件回調(diào)函數(shù)");
// this.messages.push(msg);
// }
},
//同時(shí)我們也可以在events中注冊(cè)子組件自定義事件監(jiān)聽(tīng)回調(diào)
events:{
"child-msg":function(msg){
this.messages.push(msg);
this.parentprop=msg;
console.log("子組件事件被觸發(fā)");
}
}
})