关于vue的bus网上有很多文章,但是都或多或少有点问题,这边整合了一下,整理出了我想要的版本:
起因:vue route跳转的时候使用公交事件的话,老是会存在,时间差问题导致,组件A的事件已经发送,但是组件B却还没有开始监听,要么就是因为注册后,没有取消监听,导致多次触发事件,
看了一些文章受到了一下2个文章的启发,总结了解决方案
https://www.jianshu.com/p/fde85549e3b0
https://segmentfault.com/a/1190000016992424#
代码如下:
在bus/index.js下
import Vue from 'vue'
const Bus = new Vue();
export default Bus;
export const BusEmitMixin = {
data() {
return {
bus_emit_arr: [] // 需要发射的数组
}
},
methods: {
/**
* 同级组件通讯,提交事件
* @param {String} component 要提交的目标组件名称
* @param {string} action 要调用目标组件的方法名
* @param {any} param 目标组件的方法参数
*/
BusEmit(component, action, ...param) {
this.bus_emit_arr.push([component, action, ...param]);
}
},
//在比如route跳转之后调用BusEmit跳转就发射事件
deactivated() {//这里由于我是有用vue-route,没有用的话,可以考虑beforeDestroy
this.bus_emit_arr.forEach(function ([component, action, ...param]) {
Bus.$emit(component, action, param);
})
this.bus_emit_arr = [];//清空发射的数组
}
}
/**
* 同级组件通讯,监听销毁事件
*/
export const BusOnMixin = {
//必须在这边进行监听
beforeMount() {
Bus.$on(`${this.$options.name}`, this.onBusAction);
},
//必须进行事件解绑,不然会一直存在
beforeDestroy() {
Bus.$off(`${this.$options.name}`, this.onBusAction);
},
methods: {
onBusAction(action, param) {
this[action](...param);
}
}
};
组件A->B 示例:
组件A调用示例:
import {BusEmit, BusEmitMixin} from "@common@/bus";
export default {
name: 'template_management',
mixins: [BusEmitMixin],
methods: {
send(){
this.$router.push({
name: 'send_task',
query: {
title: "新建"
}
});
this.BusEmit('send_task', 'changeTemplateId',8,'额外的参数');
}
}
}
组件b示例:
import { BusOnMixin} from "@common@/bus";
export default {
name: 'send_task',
mixins: [BusOnMixin],
methods: {
changeTemplateId(template_id,param){
console.log(template_id);//8
console.log(param);//额外参数
}
}
}
这样使用vue的bus的时候就不在那么繁琐.