vue組件間事件派發與接收

在vue的開發中,經常會在兩個組件間進行事件的通信
在vue1.0中我們使用dispatch 和broadcast

child.vue:

this.$dispatch('eventName',this.data);

parent.vue:

event:{
 'eventName':function(data) {
 // 執行的方法
 }
}

但是在vue2.0中dispatch 和broadcast被棄用,因爲基於組件樹結構的事件流方式實在是讓人難以理解,並且在組件結構擴展的過程中會變得越來越脆弱,並且這隻適用於父子組件間的通信。官方給出的最簡單的升級建議是使用集中的事件處理器,而且也明確說明了 一個空的vue實例就可以做到,因爲Vue 實例實現了一個事件分發接口


在vue2.0中在初始化vue之前,給data添加一個 名字爲eventhub 的空vue對象

new Vue({
 el: '#app',
 router,
 render: h => h(App),
 data: {
 eventHub: new Vue()
 }
})

某一個組件內調用事件觸發

this.$root.eventHub.$emit('eventName', event.target);

另一個組件內調用事件接收, 在組件銷燬時接除事件綁定,使用$off方法
介紹一個全棧開發交流學習圈,歡迎加入Q羣:864305860

created() {
 this.$root.eventHub.$on('eventName',(target) => {
 this.functionName(target)
 });
},
method:{
 functionName(target) {
 console.log(target);
 }
}

結語

感謝您的觀看,如有不足之處,歡迎批評指正。

加入我們一起聊天吹水學習

爲了幫助大家讓學習變得輕鬆、高效,大家可以加入我們交流圈子吹水學習交流:619586920歡迎大家進羣交流討論,學習交流,共同進步。

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