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()

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章