Home

Awesome

Vue.js Events Plugin

npm version vue 2.x build status minzipped size code style: standard + prettier

Simple global event bus for Vue.js applications with automatic subscription control. Zero dependencies.



Installation

npm install --save vue-plugin-events

Setup

Bundler (Webpack, Rollup)

import Vue from 'vue'
import VueEvents from 'vue-plugin-events'

Vue.use(VueEvents)

Browser

<!-- Include after Vue -->
<!-- Local files -->
<script src="vue-plugin-events/dist/vue-plugin-events.umd.js"></script>

<!-- From CDN -->
<script src="https://cdn.jsdelivr.net/npm/vue-plugin-events"></script>

Usage

Listening to Events

The plugin will automatically subscribe a component to events defined within its body. This is achieved using a new section named events. When your component is destroyed, so are any listeners that have been automatically created.

The handlers follow a pattern similar to component watch section.

// MyComponent.vue
export default {
  data: () => ({
    myValue: 'anything'
  }),
  methods: {
    doSomething (arg) { /*...*/ }
  },
  events: {

    // will execute method `doSomething` when event named `someEvent` is emitted
    someEvent: 'doSomething',

    // will fire when event named `someHandledEvent` is emitted
    someHandledEvent (v) {
      this.doSomething(v)
    },

    // will fire when event named `immediateEvent` is emitted, and as
    // soon as the component is loaded and this section is evaluated,
    // much like `immediate` option from watchers
    immediateEvent: {
      immediate: true,
      handler (v) {
        this.doSomething(v)
      }
    },

    // will fire when a `justOnceEvent` is fired, and then won't fire again;
    // may fire twice if combined with `immediate`
    justOnceEvent: {
      once: true,
      handler (v) {
        console.log('arg is', v)
      }
    }

  }
}

Emitting Events

Every component will be inject with an instance of $event, which allows the developer to emit events into the application-wide event bus. Any components listening to the emitted event will be triggered. More details can be seen in the API section below.

The methods exposed by $event below are basically the same as normal event methods in a Vue component, but instead of having only the parent component as a listeners, any component can subscribe to any events.

// AnyComponent.vue
export default {
  // ...
  methods: {
    onSomething () {
      this.$events.emit('someEvent', this.payload)
    }
  },
  // ...
}

API ($events)

.emit

.on

.once

.off

License

ISC © 2019 Ricardo Nolde