A dead-simple event bus for Vue 2.
Install VueBus with yarn or npm:
yarn add @phanan/vuebus
# or
npm install @phanan/vuebusFirst, import and initialize a new VueBus instance:
import VueBus from '@phanan/vuebus'
const bus = new VueBus()bus.emit('userLoggedIn')
bus.emit('userLoggedIn', 'with', 'additional', data)With VueBus, you can listen and react to one event:
bus.on('userLoggedIn', () => this.sayHello())or an array of events:
bus.on(['userLoggedIn', 'userLoggedBackIn'], () => this.sayHello())By passing an object of { eventName: callbackFunction } shape, you can listen to several events and react to each of them with a different callback:
bus.on({
userLoggedIn () {
this.sayHello()
},
userLoggedOut () {
this.sayGoodbye()
}
})VueBus's once and off behave exactly like their Vue counterparts.
VueBus can attach itself to Vue.prototype and become available as an instance property with the attach function . By default, you can access VueBus as this.$vuebus, but the property name can be customized by passing a string as an argument.
(new VueBus()).attach()
// VueBus is now available as a Vue's instance property
this.$vuebus.emit('userLoggedIn')
// Use a custom property name
(new VueBus()).attach('$bus')
this.$bus.emit('userLoggedIn')MIT © Phan An