vue2升级vue3: Event Bus 替代方案

5 篇文章 0 订阅
1 篇文章 0 订阅

在看 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

mitt vs tiny-emitter | npm trends
 

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源码分析Emitter事件派发---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)}

具体参看:GitHub - scottcorgan/tiny-emitter: A tiny (less than 1k) event emitter library

转载本站文章《vue2升级vue3: Event Bus 替代方案》,
请注明出处:vue2升级vue3: Event Bus 替代方案 - vue3学习笔记 - 周陆军的个人网站

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值