Simple event handling for Vue.js

Last update: Apr 20, 2022

vue-events

A Vue.js plugin that simplify events.

Works with both Vue 1.0 & Vue 2.0.

Installation

1.) Install package via Yarn or NPM
$ yarn add vue-events

$ npm install vue-events
2.) Install plugin within project.
import Vue from 'vue'
import VueEvents from 'vue-events'
Vue.use(VueEvents)

window.Vue = require('vue')
require('vue-events')

Methods

Method Params Description Docs
vm.$events.$emit event, payload Emit the event with the given payload. vm.$emit
vm.$events.emit event, payload Emit the event with the given payload. Alias for vm.$events.$emit vm.$emit
vm.$events.fire event, payload Emit the event with the given payload. Alias for vm.$events.$emit vm.$emit
vm.$events.$on event, callback Listen for the event with the given callback. vm.$on
vm.$events.on event, callback Listen for the event with the given callback. Alias for vm.$events.$on vm.$on
vm.$events.listen event, callback Listen for the event with the given callback. Alias for vm.$events.$on vm.$on
vm.$events.$off event, callback Remove event listener(s) for the event vm.$off
vm.$events.off event, callback Remove event listener(s) for the event. Alias for vm.$events.$off vm.$off
vm.$events.remove event, callback Remove event listener(s) for the event Alias for vm.$events.$off vm.$off

Usage

The $events prototype object.

This plugin extends Vue.prototype to include a new $events object, which is a just a plain vm that will serve as your global event bus. The $events vm has a couple aliases for the standard event methods.

Firing an event

There are 3 methods that fire events.

Note: $events.fire & $events.emit are aliases for $events.$emit

new Vue({

  data() {
    return {
      eventData: {
        foo: 'baz'
      }
    }
  },

  mounted() {
    this.$events.fire('testEvent', this.eventData);
    this.$events.emit('testEvent', this.eventData);
    this.$events.$emit('testEvent', this.eventData);
  }

})

Listening for an event

There are 3 methods that register event listeners.

Note: $events.listen & $events.on are aliases for $events.$on.

new Vue({
  mounted() {
    this.$events.listen('testEvent', eventData => console.log(eventData));
    this.$events.on('testEvent', eventData => console.log(eventData));
    this.$events.$on('testEvent', eventData => console.log(eventData));
  }
})

Removing an event listener

There are 3 methods that remove event listeners.

Note: $events.off & $events.remove are aliases for $events.$off.

new Vue({
  mounted() {
    this.$events.on('testEvent', eventData => console.log(eventData));
  },

  beforeDestroy() {
    this.$events.$off('testEvent')
    this.$events.off('testEvent')
    this.$events.remove('testEvent')
  }
})

The events component options.

Provide an events map as part of your component options and vue-events will automatically call $on when the component is mounted and $off when the component is destroyed.

new Vue({
  events: {
    testEvent(eventData){
       console.log(eventData)    
    }
  }  
})

Inside the event handlers, this is bound to the component instance. This way you can access your component's data, props, computed, methods, etc. For example:

new Vue({
  events: {
    onShowAlert(message){
       this.modalVisible = true
       this.message = message
    }
  }  
})

Demo

If you'd like to demo vue-events try vue-mix

License

MIT

GitHub

https://github.com/cklmercer/vue-events
Comments
  • 1. [Feature Request] Add support for "events" object in each vue

    This is a bit hard to explain, but basically in VueJS 1, the events object was an alias for .on, or whatever the function name was. It would be amazing if that was supported through this plugin.

    events: {
            'alert': function(msg) {
                this.alerts.unshift(msg)
            },
            'removeAlert': function(msg) {
                this.alerts.$remove(msg)
            },
        },
    

    Please tell me if you want me to elaborate, as this was poorly explained

    Reviewed by ajusa at 2016-08-13 13:00
  • 2. $off not working Vue.js 2

    Hey There,

    Thanks for the plugin, I'm having an issue unsubscribing from events tho.

    In one component route I have in the mounted function:

    this.$events.$on('integrations-xpm-connected', (data) => {
           console.log('test');
          });
    

    Then in the beforeDestroy function:

    this.$events.$off('integrations-xpm-connected');
    

    However, if I navigate to a new route, then come back, the event gets fired twice when called.

    if I call this.$events.$off() with no particular event specified, it unsubscribes.

    Any ideas?

    Reviewed by sn0rcha at 2017-05-20 07:44
  • 3. Events options not registering on Vue 2.2.1

    While experimenting with:

    https://github.com/ratiw/vuetable-2-tutorial-bootstrap/tree/master/src

    and running Vue 2.2.1 (latest as of this date).

    This is basically a Vue equivalent to the DataTables jquery plugin that uses vue-events. In simple terms, this consists of a Vuetable component which displays some data in a table and a FilterBar component which allows the user to enter some search criteria (free-form text).

    The FilterBar is organized as a child of the Vuetable component. When the user types data into the search field and clicks "go" a custom event called "filter-set" is emitted. The parent Vuetable component uses vue-events to listen to that event and fetch new data and reload the table.

    The problem is that, although the FilterBar is in fact emitting the event, the Vuetable component would not respond to the event and reload the table.

    I traced the problem to a conditional in vue-events (index.js) that is apparently trying to determine whether the installation is Vue 1.x or 2.x. When I comment out that conditional and just let the Vue.mixin() call run, everything works.

    I'm new to Vue so I don't fully understand Vue internals in depth yet, but it's clear something has changed such that Vue.prototype._mount does not exist (or more technically isn't considered a function) so the test fails and nothing is registered. That logic needs some work.

    Reviewed by dvatp at 2017-03-03 16:01
  • 4. How should I use it in a .js file?

    Hi @cklmercer , thanks for your code, and I have an issue about using the plugin. In component A:

    mounted () {
      this.$events.on('sucess', this.eventData);
    }
    

    in component B:

    import { doSomething } from './foo.js';
    export default {
      created () {
        doSomething();
      }
    };
    

    and in foo.js file:

    export function doSomething () {
      // some code
      this.$events.emit('sucess', data);
    }
    

    or in foo.js file:

    import Vue from 'vue';
    export function doSomething () {
      // some code
      Vue.$events.emit('sucess', data);
    }
    

    while running this project, there will be an error Uncaught TypeError: Cannot read property 'emit' of undefined. so how should I use it in foo.js file currently?

    Reviewed by aisin at 2017-09-09 11:00
  • 5. Event Extensions

    Thanks for vue-events, this plugin reminds me of a possible way to implement the suggestion/request in the following issue: https://github.com/vuejs/vue-rx/issues/5

    It would be awesome to attach robust support for RxJS observables directly into the Vue event system, any feedback on the best way to do that is most appreciated.

    NOTE: There is the vue-rx plugin, but it seems to curtail the full usage of RxJS in Vue by it's overly simple way of just auto subscribing to any observable it discovers.

    Reviewed by zoomclub at 2016-08-09 23:51
  • 6. Destroy event listener

    Events won't be destroyed when used with vue-router and you go to new route.

    On Both pages i listen to an event called from a pagination component. When i start on 1 page and go the the second page the event listener in page 1 will still fire.

    Reviewed by andredewaard at 2017-02-02 11:46
  • 7. Can v-on be modified to use global events bus

    Vue supports inline declaration of events in the html as below:

    <div class="parent"> <child-component @custom-event="customEventHandler"> </div>

    The customEventHandler being a method in the parent component. But this works only if the event is emitted on the current vue instance. If we use global event bus like vue-events then we can not have such declaration.
    My question is can the v-on or shorthand '@' be modified to catch the events from the global event bus and have the luxury of using such declarative syntax?

    Reviewed by neeravp at 2016-10-30 09:46
  • 8. Automatic event unsubscribing in Vue 2 when used in options

    This pull request will enable automatic event unsubscription when used in this manner:

    Test.vue

    <template></template>
    <script>
    export default {
      name: 'test',
      events: {
        disconnected() {
          // Do something here...
        }
      }
    }
    </script>
    

    Currently the events aren't unsubscribed -- Which is especially a problem when using HMR.

    Reviewed by mattmccray at 2017-04-02 21:10
  • 9. events fire twice

    Hey guys, am using vue events in Nuxt js and everything is working fine except that when i fire and event it is reacting twice more like it is listening to the event twice.

    How can i resolve this?

    Reviewed by mbengchan at 2018-08-24 18:51
  • 10. Events don't show up in Vue debugger

    I had to take a break from my project for few months. I'm back at it now and recently accepted an upgrade to Vue from 2.3.4. to 2.5.7.

    Since that time I've noticed a few things, one of which is relevant to vue-events. I can't seem to see the events generated through vue-events in the Vue debugging extension for Chrome anymore (on the Events tab). Not sure why. I have verified that the events ARE being emitted and received by various components, so vue-events appears to be working -- it's just that there is no way to see the events or their payloads in the debugger anymore.

    Not sure this is a problem with vue-events, but I'm curious if anyone else working with vue-events and Vue 2.5.7 or later can see events generated by vue-events in the debugger.

    Reviewed by dvatp at 2017-11-26 23:24
  • 11. Error: cannot redefine property: $events

    If I use this package in 2 different libraries and then use this 2 librares in another one then thw following problem occurs:

    index.js:104 Uncaught TypeError: Cannot redefine property: $events
        at Function.defineProperty (<anonymous>)
        at plugin (index.js:104)
        at Function.Vue.use (vue.common.js:4618)
        at Object.disposed (index.js:148)
        at __webpack_require__ (bootstrap 7ecffedbdf2f7047c51d:19)
        at Object.disposed (forge-bootstrap.js:1)
        at __webpack_require__ (bootstrap 7ecffedbdf2f7047c51d:19)
        at Object.<anonymous> (app.js:18)
        at __webpack_require__ (bootstrap 7ecffedbdf2f7047c51d:19)
        at Object.<anonymous> (app.js:25575)
    

    Any clue how can I solve this problem?

    Reviewed by acacha at 2017-11-04 20:46
Tiny simple central event bus plugin for Vue.js

vue-bus A tiny simple central event bus plugin for Vue.js (requires Vue >= 2.0). The plugin realise Non Parent-Child Communication. (655 byte gzip) In

Aug 8, 2022
The event manager for Vue.js

vue-event-manager The plugin for Vue.js provides a declarative way to bind events to a global event manager. It uses the Vue lifecycle to automaticall

Apr 23, 2022
A Vue js Global Event Bus plugin using the power of Observable

Vue-geb - Global Event Bus Vue-geb is a vue Global Event Bus plugin to help broadcast events across the app using the power of observables. Only add 5

Jan 14, 2021
Helper function for emitting events in Vue.js (functional) components

Vue emit Helper function to emit events from Vue.js functional components. Can be used in regular components too. CodeSandbox demo Installation yarn a

Mar 31, 2022
Event handling plugin for VueJS

A Vue.js plugin that provides a global event bus and a couple helper methods. Works with both Vue 1.0 & Vue 2.0. Installation 1.) Install package via

Jul 30, 2020
Event portal for associations that enables an information flow to the members and to simplify the member and event management

EventPortal Event portal for associations that enables an information flow to the members and to simplify the member and event management. Starting Vu

Feb 21, 2022
A simple Vue 3 plugin for handling browser cookies with typescript support

A vue 3 plugin for handling browser cookies with typescript support. Load and save cookies within your Vue 3 application

Aug 2, 2022
Simple, quick custom directive for handling currency format inside text inputs.

Vue-currency-directive Simple, quick custom directive for handling currency format inside text inputs. Compatible with Vue 2.x Demo/Playground Install

Mar 31, 2022
Vue.js library for handling REST service requests and model definitions.

Vue service model Vue.js Library for handling REST service requests with caching, aggregation and model definitions. Features Define models and easily

Jan 15, 2022
A tiny library for handling JSONP request.

Vue-jsonp A tiny library for handling JSONP request. Quick Start As Vue plugin: import { VueJsonp } from 'vue-jsonp' // Vue Plugin. Vue.use(VueJsonp)

Aug 7, 2022
A lightweight library for handling hierarchical content. With full customizations of items rendering.
A lightweight library for handling hierarchical content. With full customizations of items rendering.

A lightweight library for handling hierarchical content. With full customizations of items rendering.

Jun 2, 2022
Asynchronous form handling and validation for VueJS forms

Asynchronous form handling and validation for VueJS forms

Sep 24, 2019
Tiny simple central event bus plugin for Vue.js

vue-bus A tiny simple central event bus plugin for Vue.js (requires Vue >= 2.0). The plugin realise Non Parent-Child Communication. (655 byte gzip) In

Aug 8, 2022
A component to use Vue.js with Jupyter Lumino (PhosphorJS), integrating DOM & VDOM through event listeners and Vue reactivity system.
A component to use Vue.js with Jupyter Lumino (PhosphorJS), integrating DOM & VDOM through event listeners and Vue reactivity system.

vue-lumino An example project showing one way to integrate Vue.js and Lumino (née PhosphorJS). Lumino “is a library for building interactive web appli

Jul 1, 2022
Vue Directive to move the DOM without losing all the VM data, event, etc. it's Adopted from https://github.com/rhyzx/vue-transfer-dom

Vue Move DOM Vue Directive to move the DOM without losing all the VM data, event, etc. it's Adopted from vue-transfer-dom just Simplify it and change

Jun 5, 2021
Vue event bus plugin listening for online/offline changes
Vue event bus plugin listening for online/offline changes

vue-connection-listener Vue event bus plugin listening for online/offline changes About Whenever the navigator's connection status changes a 'connecti

Jul 15, 2022
🔲 Vue directive to react on clicks outside an element without stopping the event propagation

v-click-outside Vue directive to react on clicks outside an element without stopping the event propagation. Great for closing dialogues and menus amon

Aug 8, 2022
Vue directive plugin for drag event detection.

v-dragged Vue directive plugin for drag event detection. NOTE: This directive listens for mouse/touch events, and sets a handler for when a drag actio

Aug 11, 2022
:running: Vue.js directive to add a document event listener on escape keyup.

vue-esc ?? Vue.js directive to add a document event listener on escape keyup. Support Vue.js 2 => [email protected]>=2.0.0 [master] Vue.js 1 => [email protected] I

May 5, 2022
Event-Based communication across opened tabs for Vue 2.x
Event-Based communication across opened tabs for Vue 2.x

vue-tabevents Easy communication between tabs for Vue 2.x Getting Started Installing Install with npm: npm install --save vue-tabevents import into pr

Jul 2, 2022