Create global event bus in Nuxt.js

Created By Nikunj Kanetiya  |  Last Updated on : 2019-01-11

Objective

How to create a global event bus in nuxt.js.

If you are looking to create an event bus for events emit & listening through-out your nuxt application here is the way you can do that.

create bus.js in the plugins directory

import Vue from 'vue'

const eventBus = {}

eventBus.install = function (Vue) {
  Vue.prototype.$bus = new Vue()
}

Vue.use(eventBus)


now register your plugin in nuxt.config.js

/*
** Plugins to load before mounting the App
*/
plugins: [
  '~/plugins/bus'
],

That's it. now use it anywhere
 

// Event emit
this.$bus.$emit('test-event')
or
app.$bus.$emit('test-event')

// Event Listen
this.$bus.$on('test-event', () => {})

  

Created on : 2019-01-11
Written by

Nikunj Kanetiya

Full Stack Web Developer

Tags
nuxt.js
vue.js
event bus
event
global event bus
nuxt plugin