首页 > 技术文章 > vue2升级vue3: Event Bus 替代方案

zhoulujun 2022-06-21 20:26 原文

在看 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 it's 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 interfacefor example mitt or tiny-emitter.

 

mitt vs tiny-emitter

https://www.npmtrends.com/tiny-emitter-vs-mitt

WX20220615-144427.jpg

mitt 和 tiny-emitter 对比分析

共同点

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

不同点

  • emit

    1. 有 all 属性,可以拿到对应的事件类型和事件处理函数的映射对象,是一个Map不是{}

    2. 支持监听'*'事件,可以调用emitter.all.clear()清除所有事件

    3. 返回的是一个对象,对象存在上面的属性

  • tiny-emitter

    1. 支持链式调用, 通过e属性可以拿到所有事件(需要看代码才知道)

    2. 多一个 once 方法 并且 支持设置 this(指定上下文 ctx)

    3. 返回的一个函数实例,通过修改该函数原型对象来实现的

更多参看:mitter事件派发---mitt和tiny-emitter源码分析https://juejin.cn/post/7022851362568454157

 

看官方代码案例是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)}

具体参看:https://github.com/scottcorgan/tiny-emitter

 


转载本站文章《vue2升级vue3: Event Bus 替代方案》,
请注明出处:https://www.zhoulujun.cn/html/webfront/ECMAScript/vue3/8837.html

推荐阅读