Vue 中非父子元件間的傳值
匯流排機制
非父子之間傳值,可以採用釋出訂閱模式
,這種模式在 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()