EventBus for Nuxt.js components
Nuxt.js is server-rendered framework build on the top of Vue.js and it extends all the features of Vue.js.
Nuxt.js presets all the configuration needed to make your development of a Vue.js Application Server Rendered more enjoyable.
In Nuxt.js Application communication between components can be done Using following ways -
Communication between Parent to Child components can be done using props, and the EventBus can be use for event up i.e. Child to Parent components but the Vuex is more robust by which we can manage the state of entire application.
Here, I’m going to explain how can you use the EventBus to communicate between Non Parent-Child component in Nuxt.js.
EventBus allows us to communicate between two components using events. It also allow us to emit an event with data or we can say the payload from one component and listen for that event and receive the data in another.
Let’s take an example and emit an event on button click from ComponentA with updated click count and try to receive it at ComponentB which is parent component of ComponentA with updated click count.
I’m using a single-file-component here, but you can use whatever method of creating components you’d like.
EventBus can be segregated in two sections — propagating an event and receiving an event.
As shown in below code — In ComponentA (child) on Increment Count button click we will emit an event with the name ‘INC_COUNT’ and send the current click count with the method.
Now any component can listen the emitted event ‘INC_COUNT’.
The $emit method take two parameters one is ‘EVENT_NAME’ and other is payload means any data if you want to send to other component. Here, payload can be any value like String, Array, Object, etc.
As shown in the below code — In ComponentB (parent) wants to listen the emitted event and display the click count. Which will be achieve with $on method on component’s created or mounted hooks with the same event name ‘INC_COUNT’ which is emitted from ComponentA as shown in below code.
Same as $emit method $on also has two parameters one ‘EVENT_NAME’ and other the callback function which brings an emitted data. Also, you can turned off event listener by using $off method before you destroying the component.
$off method can have two parameters:
- If no arguments are provided, remove all event listeners.
- If only the event is provided, remove all listeners for that event.
- If both event and callback are given, remove the listener for that specific callback only.