45 lines
967 B
TypeScript
Raw Normal View History

2025-03-11 10:29:43 +08:00
import { onUnmounted } from 'vue';
import mitt from 'mitt';
type IEventbus = {
publish: (eventName: string, content: any) => void;
subscribe: (eventName: string, callback: (content: any) => void) => void;
};
const emitter = mitt();
/**
* @description:
* @param {*} eventName
* @param {*} content
*/
const publish = (eventName: string, content: any) => {
emitter.emit(eventName, content);
};
/**
* @description:
* @param {*} eventName
* @param {*} callback
*/
const subscribe = (eventName: string, callback: (content: any) => void) => {
emitter.on(eventName, (content) => callback(content));
};
/**
* @description: useEventbus
*/
export const useEventbus = (): IEventbus => {
// 销毁的事件
onUnmounted(() => {
// 清空所有的事件,避免多组件互相清理
emitter.all.clear();
});
return {
publish,
subscribe,
};
};