vue2升级vue3: Event Bus 替代方案

在看 https://v3-migration.vuejs.org/breaking-changes/events-api.html

在vue2里面

In 2.x, a Vue instance could be used to trigger handlers attached imperatively via the event emitter API ($on, $off and $once). This could be used to create an event bus to create global event listeners used across the whole application: // eventBus.js const eventBus = new Vue() export default eventBus 直接在项目使用 eventBus.$on(custom-event, () => {//TODO}) eventBus.$emit(custom-event)

但是,vue3移除了

We removed $on, $off and $once methods from the instance completely. $emit is still a part of the existing API as its used to trigger event handlers declaratively attached by a parent component. The event bus pattern can be replaced by using an external library implementing the event emitter interface, for example or .

mitt vs tiny-emitter

mitt 和 tiny-emitter 对比分析

共同点

  1. 都支持on(type, handler)、off(type, [handler])和emit(type, [evt])三个方法来注册、注销、派发事件

不同点

    emit 有 all 属性,可以拿到对应的事件类型和事件处理函数的映射对象,是一个Map不是{} 支持监听*事件,可以调用emitter.all.clear()清除所有事件 返回的是一个对象,对象存在上面的属性 tiny-emitter 支持链式调用, 通过e属性可以拿到所有事件(需要看代码才知道) 多一个 once 方法 并且 支持设置 this(指定上下文 ctx) 返回的一个函数实例,通过修改该函数原型对象来实现的

更多参看:mitter事件派发---mitt和tiny-emitter源码分析

看官方代码案例是tiny-emitter

$emit 目前只能从子组件向父组件传值了,event Bus 只有借助第三方库了

// eventBus.js
import emitter from tiny-emitter/instance
export default {
  $on: (...args) => emitter.on(...args),
  $once: (...args) => emitter.once(...args),
  $off: (...args) => emitter.off(...args),
  $emit: (...args) => emitter.emit(...args)}

具体参看:

经验分享 程序员 微信小程序 职场和发展