非父子組件之間的通信
上面我們使用props只能解決父子組件之間的通信,當(dāng)兩個(gè)兄弟關(guān)系的組件,就不能這樣傳遞了
兄弟節(jié)點(diǎn)之間需要使用 事件的觸發(fā)方法 $emit去實(shí)現(xiàn)
先看代碼:具體解釋在注釋中
看下面這句話
代碼中,我們聲明了一個(gè)獨(dú)立的空Vue公用實(shí)例,用來觸發(fā)通訊的事件。在a組件中使用 $emit觸發(fā)事件,在 c組件中使用on監(jiān)聽事件,就可以實(shí)現(xiàn)數(shù)據(jù)的傳遞了。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
</head>
<body>
<div id="box">
<com-a></com-a> <!-- 調(diào)用com-a組件 -->
<com-c></com-c><!-- 調(diào)用com-c組件 -->
</div>
<script>
var Event=new Vue(); // 聲明一個(gè)獨(dú)立的空Vue公用實(shí)例,用來觸發(fā)通訊的事件
var a={
template:'<div><span>我是a組件,我的數(shù)據(jù)內(nèi)容是{{msga}}</span><br><input type="button" value="我要發(fā)送數(shù)據(jù)" @click="send"></div>',
data(){
return{
msga:'我是a數(shù)據(jù),我要發(fā)送給兄弟組件'
}
},
methods:{
send(){
Event.$emit('a-msg',this.msga) //觸發(fā)前面 Event 公用示例的方法,那么別的地方就可以想辦法監(jiān)聽接收這個(gè)事件。參數(shù)(事件名,傳輸?shù)闹担? }
}
};
var c={
template:"<div><h3>這是C組件</h3><span>我從A里面接受的數(shù)據(jù):{{a}}</span></div>",
data(){
return{
a:''
}
},
mounted(){ //這里的mouted表示當(dāng)組件和頁面掛載完成的時(shí)候,需要執(zhí)行的函數(shù)
var _this = this; //因?yàn)樵贓vent.on內(nèi)部的this是指向 Event實(shí)例的,所以這里,先使用 _this將this存起來,后面就可以使用了。
Event.$on('a-msg',function (a) { //使用on監(jiān)聽事件 a-msg,這樣當(dāng)a組件中使用 emit主動(dòng)觸發(fā)了 Event實(shí)例的a-msg事件之后,這里就可以接收到
alert('觸發(fā)了接收');
_this.a = a;
})
}
};
new Vue({
el:'#box',
components:{
'com-a':a,
'com-c':c
}
})
</script>
</body>
</html>