Vue 利用provide实现事件bus

Vue 利用provide实现事件bus

徐徐
前端
发布于2024-08-28 17:00:07
🌺前言
Vue 利用provide实现事件bus,不用依赖其他插件

typescript
import { inject } from "vue";
export interface EventBus {
  $on(event: string, callback: (...args: any[]) => void): void;
  $emit(event: string, ...args: any[]): void;
}

const createEventBus = () => {
  const events: Record<string, Function[]> = {};

  const $on = (event: string, callback: (...args: any[]) => void) => {
    if (!events[event]) {
      events[event] = [];
    }
    events[event].push(callback);
  };

  const $emit = (event: string, ...args: any[]) => {
    if (events[event]) {
      events[event].forEach((callback) => callback(...args));
    }
  };

  return { $on, $emit };
};

export function provideEventBus(app: any) {
  const eventBus:EventBus = createEventBus();
  app.provide("eventBus", eventBus);
}

export function useEventBusInject() {
  return inject<EventBus>("eventBus");
}
文章最后更新于 2024-08-28 17:00:07
留言
暂无数据

~~空空如也