1. vue2中使用了,很多bus,在有些地方忘记清理了,导致重复事件bug. 对bus进行改造,实现清除遗留. 下面的简单实现.
1.eventbus.js
// eventBus.js
import Vue from 'vue';
class EventBusClass extends Vue {
constructor() {
super();
this.listeners = [];
}
on(event, callback, context) {
this.$on(event, callback);
this.listeners.push({ event, callback, context });
}
off(event, callback, context) {
this.$off(event, callback);
this.listeners = this.listeners.filter(listener =>
listener.event !== event || listener.callback !== callback || listener.context !== context
);
}
clear(context) {
this.listeners = this.listeners.filter(listener => {
if (listener.context === context) {
this.$off(listener.event, listener.callback);
return false;
}
return true;
});
}
}
const EventBus = new EventBusClass();
export default EventBus;
2. main.js使用
import Vue from 'vue'
import App from './App.vue'
import EventBus from "./EventBusManage";
import ElementUI from 'element-ui';
import * as echarts from 'echarts';
import 'element-ui/lib/theme-chalk/index.css';
Vue.prototype.$bus = EventBus
Vue.use(ElementUI);
Vue.config.productionTip = false
Vue.prototype.$echarts = echarts
new Vue({
render: h => h(App),
}).$mount('#app')
3.调用测试
发送事件
接收事件1
接收事件2