前言

三个兄弟组件通信

EventBus未勾销绑定,反复触发的bug

根本应用

/新建一个 js 文件,写下如下代码就创立好了一个 eventbus,没错,就是这么简略import Vue from 'vue'export default new Vue;

全局调用

在 main.js 中导入 eventbus ,而后将它挂载到 vue 的原型上,这样就能够全局调用了

import bus from './utils/eventBus'Vue.prototype.bus = bus;

其余文件

//发送this.bus.$emit(this.$route.path);//接管this.bus.$on(this.$route.path,()=>{  this.getData();})//销毁beforeDestroy() {  //组件销毁前须要解绑事件。否则会呈现反复触发事件的问题  this.bus.$off(this.$route.path);},

简略调用

import bus from './utils/eventBus'//发送bus.$emit('get', {  item: item.type,  date: date})//接管bus.$on('get', this.myhandle)//销毁beforeDestroy() {  //组件销毁前须要解绑事件。否则会呈现反复触发事件的问题  bus.$off('get');},

尤大大提出了以下解决

// 在B组件页面中增加以下语句,在组件beforeDestory的时候销毁。beforeDestroy () {  bus.$off('get', this.myhandle)},

如果想要用bus 来进行页面组件之间的数据传递,须要留神亮点,组件A$emit事件应在beforeDestory生命周期内。其次,组件B内的$on记得要销毁。

解决教训

1:尽管尤大大解决方案能销毁$on,然而多个eventbus,解决不慎,容易导致事件不能再次触发;

2:多个eventbus,多个组件实时交互,解决逻辑简单;

3:弹窗还有其余逻辑交换,多功能组件不适宜应用eventbus,须要利用vuex实时交互;

4:保护艰难

5:除非非常简单逻辑,否则不倡议应用eventbus

Vue EventBus传值的bug(EventBus踩坑).md)