EventBus最简单实现

585#1072e8ba

“Vue组件通信有那些方式?”;“父->子:props/$refs,子->父:$parent/$emit,多级组件:Vuex/Event Bus”;“好的,简单实现一下Event Bus”;“...”

: “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();

参与本文讨论

请先登录 GitHub 后留言

0/500

本文留言

0

这篇文章还没有留言,来写第一条吧。

1 / 1