EventBus最简单实现
: “Vue组件通信有那些方式?”
:“父->子:props/refs,子->父:parent/$emit,多级组件:Vuex/Event Bus”
:“好的,简单实现一下Event Bus”
:“...”
那就花几分钟简单描述下吧!
ts
/* eslint-disable @typescript-eslint/ban-types */
class EventBus {
private events: Map<string, Function[]>;
constructor() {
this.events = new Map();
}
on(eventName: string, fn: Function) {
if (!eventName) {
console.error('无效的事件名称');
return false;
}
if (!(fn instanceof Function)) {
console.error('无效的回调方法');
return false;
}
const fns = this.events.get(eventName) || [];
fns.push(fn);
this.events.set(eventName, fns);
}
emit(eventName: string, ...args: any[]) {
this.events.get(eventName)?.forEach((fn) => {
fn(args);
});
}
}
export default new EventBus();