@phanan/vuebus

A simple event bus for Vue
981 8
Install
npm install @phanan/vuebus
Latest Version:3.0.1
Vue:2
License:MIT
Last Updated:Jul 21, 2022
Links: GitHub  ·  npm
Maintainer: phanan

VueBus

A dead-simple event bus for Vue 2.

Installation

Install VueBus with yarn or npm:

yarn add @phanan/vuebus
# or
npm install @phanan/vuebus

Usage

First, import and initialize a new VueBus instance:

import VueBus from '@phanan/vuebus'

const bus = new VueBus()

Emit an event

bus.emit('userLoggedIn')
bus.emit('userLoggedIn', 'with', 'additional', data)

Listen to events

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()
  }
})

once and off

VueBus's once and off behave exactly like their Vue counterparts.

Attach to Vue.prototype

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')

License

MIT © Phan An

Version History

Version Released Vue License
3.0.1 ^2.6.11 MIT
3.0.0 ^2.6.11 MIT
2.1.0 ^2.6.11 MIT
2.0.0 ^2.6.11 MIT
1.0.0 ^2.5.13 MIT