npm install --save mitt
utils/eventBus.ts
import mitt from 'mitt'
export const globalEventBus = mitt()
// 引入
import { globalEventBus } from '@/utils/eventBus'
// emit
setInterval(() => {
globalEventBus.emit('test', 1)
}, 2000)
const fn = (val) => {
console.log(val)
console.log('fn')
}
// on
globalEventBus.on('test', fn)
// off
onBeforeUnmount(() => {
console.log('onBeforeUnmount')
globalEventBus.off('test') // 生效
// globalEventBus.off('test', fn) // 生效,但fn内的代码不会执行
// globalEventBus.off('test', () => { // 不生效
// console.log('off')
// })
})
注意:
参考官网
import mitt from 'mitt'
const emitter = mitt()
// listen to an event
emitter.on('foo', e => console.log('foo', e) )
// listen to all events
emitter.on('*', (type, e) => console.log(type, e) )
// fire an event
emitter.emit('foo', { a: 'b' })
// clearing all events
emitter.all.clear()
// working with handler references:
function onFoo() {}
emitter.on('foo', onFoo) // listen
emitter.off('foo', onFoo) // unlisten