在vue的開發中,常常會在兩個組件間進行事件的通訊vue
在vue1.0中咱們使用$dispatch 和 $broadcastapp
child.vue:this
this.$dispatch('eventName',this.data);
parent.vue:spa
event:{ 'eventName':function(data) { // 執行的方法 } }
可是在vue2.0中$dispatch 和 $broadcast被棄用,由於基於組件樹結構的事件流方式實在是讓人難以理解,而且在組件結構擴展的過程當中會變得愈來愈脆弱,而且這隻適用於父子組件間的通訊。官方給出的最簡單的升級建議是使用集中的事件處理器,並且也明確說明了 一個空的vue實例就能夠作到,由於Vue 實例實現了一個事件分發接口
在vue2.0中在初始化vue以前,給data添加一個 名字爲eventhub 的空vue對象code
new Vue({ el: '#app', router, render: h => h(App), data: { eventHub: new Vue() } })
某一個組件內調用事件觸發router
this.$root.eventHub.$emit('eventName', event.target);
另外一個組件內調用事件接收, 在組件銷燬時接除事件綁定,使用$off方法對象
created() { this.$root.eventHub.$on('eventName',(target) => { this.functionName(target) }); }, method:{ functionName(target) { console.log(target); } }