wupengfei
2025-02-20 1703be93b291e4e9e380b139d236cbd9096f929b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import { useEventBus, EventBusKey, UseEventBusReturn } from '@vueuse/core';
import { InjectionKey, inject, provide, onUnmounted } from 'vue';
 
export type GlobalEvent = {
  updateInsuranceClaim: any;
  'enterprise:add': any;
  'enterprise:edit': any;
};
 
export type GlobalEventListener<T extends keyof GlobalEvent> = (payload: GlobalEvent[T]) => any;
 
export const eventKey: EventBusKey<keyof GlobalEvent> = Symbol('eventKey');
 
export type GlobalEventContext = {
  bus: UseEventBusReturn<keyof GlobalEvent, any>;
};
 
export const globalEventContextKey: InjectionKey<GlobalEventContext> = Symbol('GlobalEventContext');
 
export function useGlobalEventProvide() {
  const bus = useEventBus(eventKey);
  provide(globalEventContextKey, { bus });
}
 
export function useGlobalEventContext() {
  const { bus } = inject(globalEventContextKey);
  const subscribes: Fn[] = [];
 
  function addEvent<T extends keyof GlobalEvent>(event: T, cb?: GlobalEventListener<T>) {
    const unsubscribe = bus.on((e, payload) => {
      if (e === event) {
        cb?.(payload);
      }
    });
    subscribes.push(unsubscribe);
  }
 
  function emit<T extends keyof GlobalEvent>(event: T, payload?: GlobalEvent[T]) {
    bus.emit(event, payload);
  }
 
  onUnmounted(() => {
    subscribes.forEach((sub) => {
      sub();
    });
  });
 
  return {
    addEvent,
    emit,
  };
}