總線機制
非父子之間傳值,可以採用發佈訂閱模式,這種模式在 Vue 中被稱爲總線機制,或者叫做Bus
/ 發佈訂閱模式 / 觀察者模式
<div id="root">
<child content="Dell"></child>
<child content="Lee"></child>
</div>
Vue.prototype.bus = new Vue() //掛載 bus 屬性
Vue.component('child', {
data(){
return {
selfContent: this.content
}
},
props: {
content:String
},
template: '<div @click="handleChildClick">{{selfContent}}</div>',
methods: {
handleChildClick() {
this.bus.$emit('change',this.selfContent) // 發佈
}
},
mounted(){
this.bus.$on('change',(msg)=>{ //訂閱,這裏會被執行兩次
this.selfContent = msg
})
}
})
let vm = new Vue({
el: '#root'
})
Vue.prototype.bus = new Vue()
這句話的意思是,在 Vue 的prototype
掛載了一個bus
屬性,這個屬性指向 Vue 的實例,只要我們之後調用 Vue 或者new Vue
時,每個組件都會有一個bus
屬性,因爲以後不管是 Vue 的屬性還是 Vue 的實例,都是通過 Vue 來創建的,而我在 Vue 的prototype
上掛載了一個bus
的屬性。
組件被掛載之前會執行mounted
鉤子函數,所以可以在mounted
中對change
事件進行監聽。
this.bus.$on()
那邊會被執行兩次,原因是什麼呢?因爲在一個child
組件裏面,觸發事件的時候,外面兩個child
的組件都進行了同一個事件的監聽,所以兩個child
的組件都會執行一遍this.bus.$on()