如果你刚开始使用Vue3,很可能会发现,原本用得得心应手的eventBus突然不灵了。
因为Vue3不再提供$on
与emit
函数,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再次用起来也非常简单,大体就是三个步骤
- 引入/编写事件库
- 在入口文件中挂载
- 在组件中引入并使用