Vue3-Eventbus
Tiny event bus plugin for Vue3.
Why 使用原因
Vue3实例不再提供$on
与emit
函数,官方推荐引入外部工具实现,使用本插件可以让你更轻松的在Vue3中使用轻量且功能完善eventBus
不引入插件的用法
App instance dont't have $on
and $emit
methods anymore in Vue3.
Remove $on, $off and $once instance methods. Vue instances no longer implement the event emitter interface. -- active-rfcs/0020-events-api-change.md
So the RFC suggests using a third-party library instead. But you have to do some repetitive work for it. This tiny tool can solve this problem for you.
Install 安装
$ npm install --save vue3-eventbus
Usage 用法
use
// import {createApp} from 'vue// const app = createApp(App)app
emit
// Button.vue// or: import { bus } from 'vue3-eventbus' { // fire an event bus }
listen/unlisten
// Panel.vue { // listen to an event bus // listen to all events bus // working with handler references: {} bus // listen bus // unlisten }
Advanced Usage 更多用法
Access by instance 通过实例访问
Don't need to import vue3-eventbus
不需要import vue3-eventbus
{ this$eventBus }
Access by inject method 通过inject访问
Have to import inject
api from vue
{ const bus = bus }
Options 配置
app.use(bus, options)
defaultOptions = // Access by instance 是否挂载在全局 global: true // Access by inject 是否provide inject: true // 实例上挂载的名称 globalPropertyName: '$eventBus' // 通过inject引入的名称 injectName: '$eventBus'
example 修改挂载在应用上的名称
// main.jsapp // Button.vue { this$ev}
| | | | | | |
Native usage without vue3-eventbus
不使用vue3-eventbus插件的原生用法
// bus.js// + + + { // ... } { // ... } { // ... } // main.js// +// +app// +appconfigglobalProperties$bus = $bus // Button.vue// + { // import and inject in every component // + const $bus = $bus} // Panel.vue// + { // + const $bus = $bus} // Page.vue { const $bus = $bus}