There are many ways vue communication, there are more and more used in the project of pros、vuex、$emit/$on
these three, as well as provide/inject
(for higher-order components), $attrs和$listeners
(suitable for high-order components) and $parent/$child/ref、eventBus
so on three ways. Many times we are only using the api, and understand the principles and achieve, but I think not in the same level with the time to understand the principles and achieve a just call api developers. So here it is like the cross-component communication eventBus
Theory of Communication to show you what. This is also the chiefs of the things he learned and on this record (reproduced) it.
class EventBus{
constructor(){
this.event=Object.create(null);
};
//注册事件
on(name,fn){
if(!this.event[name]){
//一个事件可能有多个监听者
this.event[name]=[];
};
this.event[name].push(fn);
};
//触发事件
emit(name,...args){
//给回调函数传参
this.event[name]&&this.event[name].forEach(fn => {
fn(...args)
});
};
//只被触发一次的事件
once(name,fn){
//在这里同时完成了对该事件的注册、对该事件的触发,并在最后取消该事件。
const cb=(...args)=>{
//触发
fn(...args);
//取消
this.off(name,fn);
};
//监听
this.on(name,cb);
};
//取消事件
off(name,offcb){
if(this.event[name]){
let index=this.event[name].findIndex((fn)=>{
return offcb===fn;
})
this.event[name].splice(index,1);
if(!this.event[name].length){
delete this.event[name];
}
}
}
}
复制代码
The above code using a publish-subscribe model.
Reference links:
1, the interviewer Series (2): Event Bus achieve
2, a qualified mid-level front-end engineers must master the skills of 28 JavaScript