🌺前言
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
作者:徐徐版权声明:转载请注明文章出处
留言

~~空空如也