# vue3 中使用事件总线
# 1. 介绍
vue3,使用 TS 实现 事件总线(event-bus)
# 2. 示例
安装:
npm i mitt
# "mitt": "^3.0.1",
代码:
EventBus.ts:
/* eslint-disable no-param-reassign */ import { App, Plugin } from 'vue'; import mitt from 'mitt'; export const EventBusPlugin: Plugin = { install(app: App) { app.config.globalProperties.$eventBus = mitt(); }, };
main.ts:
import { createApp } from 'vue'; import { EventBusPlugin } from '..../EventBus'; import App from './App.vue'; createApp(App) .use(EventBusPlugin) .mount('#app');
src/typing.d.ts
import Vue from 'vue'; import type { Emitter } from 'mitt'; declare module '@vue/runtime-core' { interface ComponentCustomProperties { // ... $eventBus: Emitter<any> } }
# 3. 参考
上一篇: 下一篇:
本章目录