event-bus
在vue中使用时,为了避免在vue组件未实际生效时,event-bus就进行事件的监听。因此需要结合vue的生命周期进行代理实现。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| import mitt from 'mitt'
class CustomEventBus { constructor() { this.keys = {} this.emitter = mitt() }
emit(key, ...args) { this.keys[key.toUpperCase()] = key this.emitter.emit(key, ...args) }
on(key, callback) { this.emitter.on(key, callback) } onInVue(key, callback, vm) { const callbackProxy = (...args) => { if (vm._inactive) return callback(...args) } this.emitter.on(key, callbackProxy) vm.$once('hook:beforeDestroy', () => { this.emitter.off(key, callbackProxy) }) }
off(key, callback) { this.emitter.off(key, callback) } }
export default new CustomEventBus()
|