项目中使用了事件总线eventBus来进行两个组件间的通信,
使用方法是是建立eventBus.js文件,暴露一个空的Vue实例,如下:
import Vue from 'vue'
export default new Vue()
在需要通信的两个组件中分别import
import eventBus from "@/utils/eventBus";
然后就可以通过emit、on进行通信:如下:
//一个组件中发射
eventBus .$emit('open_dialog',true);
//另一个组件中接收
eventBus .$on('open_dialog', sms => {...})
其中可能会遇到一个坑是eventBus .$on()
会触发多次,具体原因跟生命周期有关;
解决办法就是在beforeDestroy或destroy周期中将事件进行销毁,使用eventBus .$off()
beforeDestroy () {
eventBus .$off('open_dialog')
},
附上github上Vue作者尤大大关于这问题的解答:
https://github.com/vuejs/vue/issues/3399