vue 设置事件总线 EventBus
有些场景下使用 EventBus 总线要让代码简单许多。
第一步:编写EventBus类
class EventBus {
constructor(){
(this as any).callbacks = {}
}
/**
* 事件总线中注册事件 singleFlag为true 表示只能注册一次 防止重复执行
* @param name
* @param fn
* @param singleFlag
*/
$on(name:any, fn:any,singleFlag=false){
if(singleFlag){
(this as any).callbacks[name] = (this as any).callbacks[name] || [];
(this as any).callbacks[name][0]=fn;
}else{
(this as any).callbacks[name] = (this as any).callbacks[name] || [];
(this as any).callbacks[name].push(fn)
}
}
/**
* 事件触发
* @param name
* @param args
*/
$emit(name:any, args:any){
if((this as any).callbacks[name]){
(this as any).callbacks[name].forEach((cb:any) => cb(args))
}
}
}
export default EventBus;
第二步:将事件总线放入到vue中,找到main.js文件加入如下代码
Vue.prototype.$bus = new EventBus();
第三步:则就是注册事件了
this.$bus && this.$bus.$on(this.sectionId + "_tabChange", ({sectionId, item}) => {
if (window.appObj.sysName === "groupAdmin") {
this.initTempDataItems();
} else {
this.initDataByUrl();
}
}, true);
//点击弹出更多界面
this.$bus && this.$bus.$on(this.sectionId + "_moreLinkClick", ({sectionId, item, moreUrl}) => {
this.jumpToPage(moreUrl);
}, true);
第四步:则就是触发事件了:
this.$bus&&this.$bus.$emit(this.sectionId+"_tabChange",{sectionId:this.sectionId,item});
还没有评论,来说两句吧...