How to make an event bus plugin in Nuxt
June 17, 2021 ยท -15 min read
Vue
Nuxt

Step 1: Create the file for the plugin

In the plugins directory of your Nuxt project create a file called bus.js, you can call this file whatever you want but it seems most logical just to call it bus.js.

Step 2: Add your plugin to nuxt.config.js

        plugins: [
            '@/plugins/bus',
            ],

Step 3: Time to code

        import Vue from 'vue'
        
        const eventBus = {}
        
        eventBus.install = function (Vue) {
          Vue.prototype.$bus = new Vue()
        }
        
        Vue.use(eventBus)

Step 4: Now use it!

The first thing you need to do is set up an event bus listener wherever you need it by doing the following:

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

Now in another component you can emit an event like so:

        this.$bus.$emit( 'test-event', payload )

It's that easy! You can now use this in your pages, components, layout, etc.