Vue 3 中如何优雅的使用eventBus(事件总线)

lxf2023-05-13 01:20:55

如果你刚开始使用Vue3,很可能会发现,原本用得得心应手的eventBus突然不灵了。

因为Vue3不再提供$onemit函数,Vue实例不再实现事件接口。官方推荐引入外部工具实现,或者自己手撸一个事件类

api变更文档

Remove $on, $off and $once instance methods. Vue instances no longer implement the event emitter interface. -- active-rfcs/0020-events-api-change.md

如何使用

想在Vue3上把EventBus再次用起来也非常简单,大体就是三个步骤

  1. 引入/编写事件库
  2. 在入口文件中挂载
  3. 组件中引入并使用