npm安装
npm i mitt
pnpm安装
pnpm i mitt
yarn安装
yarn add mitt
import mitt from 'mitt'
//创建一个事务总线
const emitter = mitt()
//触发
emitter.emit('xxx-event', { visible: false })
//监听
emitter.on('xxx-event',(data)=> console.log(data) // { visible: false })
//移除监听
emitter.off('xxx-event')
//清空所有监听
emitter.all.clear();
main.ts
import mitt from 'mitt'
const emitter = mitt()
//....
const App = createApp(app)
//挂到全局
App.config.globalProperties.emitter = emitter
xxx.vue
import { getCurrentInstance } from 'vue'
const { emitter } = getCurrentInstance()!.appContext.config.globalProperties
//触发
emitter.emit('xxx-event', { visible: false })
//监听
emitter.on('xxx-event',(data)=> console.log(data) // { visible: false })
//移除监听
emitter.off('xxx-event')
//清空所有监听
emitter.all.clear();