Tiny event bus plugin for Vue3.
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.
$ npm install --save vue3-eventbus
use
// import {createApp} from 'vue
import eventBus from 'vue3-eventbus'
// const app = createApp(App)
app.use(eventBus)
emit
// Button.vue
import bus from 'vue3-eventbus'
// or: import { bus } from 'vue3-eventbus'
export default {
setup() {
// fire an event
bus.emit('foo', { a: 'b' })
}
}
listen/unlisten
// Panel.vue
import bus from 'vue3-eventbus'
export default {
setup() {
// listen to an event
bus.on('foo', e => console.log('foo', e) )
// listen to all events
bus.on('*', (type, e) => console.log(type, e) )
// working with handler references:
function onFoo() {}
bus.on('foo', onFoo) // listen
bus.off('foo', onFoo) // unlisten
}
}
Access by instance 通过实例访问
Don't need to import vue3-eventbus
不需要import vue3-eventbus
export default {
created() {
this.$eventBus.emit('foo')
}
}
Access by inject method 通过inject访问
Have to import inject
api from vue
import `inject` from 'vue'
export default {
setup() {
const bus = inject('$eventBus')
bus.emit('foo')
}
}
app.use(bus, options)
defaultOptions = {
// Access by instance 是否挂载在全局
global: true,
// Access by inject 是否provide
inject: true,
// 实例上挂载的名称
globalPropertyName: '$eventBus',
// 通过inject引入的名称
injectName: '$eventBus'
}
example 修改挂载在应用上的名称
// main.js
app.use(bus, {
globalPropertyName: '$ev'
})
// Button.vue
created() {
this.$ev.emit('click', {time: Date.now()})
}
| | | | | | |
不使用vue3-eventbus插件的原生用法
// bus.js
// + + +
export default {
on(){
// ...
}
off(){
// ...
}
emit(){
// ...
}
}
// main.js
// +
import $bus from './lib/helpers/bus.js'
// +
app.provide('$bus', $bus)
// +
app.config.globalProperties.$bus = $bus
// Button.vue
// +
import { inject } from 'vue'
setup() {
// import and inject in every component
// +
const $bus = inject('$bus')
$bus.emit('click')
}
// Panel.vue
// +
import { inject } from 'vue'
setup() {
// +
const $bus = inject('$bus')
$bus.on('click')
}
// Page.vue
import { inject } from 'vue'
setup() {
const $bus = inject('$bus')
$bus.off('click')
}