Parag Chirde
Posted on July 15, 2022
Event bus is typically a mechanism that makes it possible to have communication between different components. These components can be present at any level of component hierarchy in your project.
To know more about Event bus and its implementation in Nuxt2 visit link
VueJS Eventbus: Easy way to pass data between components
However, the official documentation you can see how the Event Bus implementation has changed from Vue 2 to Vue 3.
Introducing mitt, a new and simple way of implementing event bus on Vue3/Nuxt3
We’ll start by installing mitt.
npm i mitt
Next we’ll register a new plugin named mitt.client.js
in the plugins directory.
import mitt from "mitt";
const emitter = mitt();
export default defineNuxtPlugin((nuxtApp) => {
nuxtApp.provide('bus', {
$on: emitter.on,
$emit: emitter.emit,
})
})
Know more about registering plugins in Nuxt3 here
Let’s see how to emit and listen to events in different components. Consider two components A and B. In our case Component A will emit the event and Component B will listen to the event.
ComponentA.js
this.$bus.$emit("someEvent", 'Data to send')
ComponentB.js
mounted() {
this.$bus.$on("someEvent", (data) => {
console.log(data);
//Some stuff to do..
}
That’s pretty neat and clean. Thank you for reading!
Posted on July 15, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.