Event bus in Nuxt3

chirdeparag

Parag Chirde

Posted on July 15, 2022

Event bus in Nuxt3

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
Enter fullscreen mode Exit fullscreen mode

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,
    })
  })
Enter fullscreen mode Exit fullscreen mode

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')
Enter fullscreen mode Exit fullscreen mode

ComponentB.js

mounted() {
this.$bus.$on("someEvent", (data) => {
    console.log(data);
    //Some stuff to do..
}
Enter fullscreen mode Exit fullscreen mode

That’s pretty neat and clean. Thank you for reading!

💖 💪 🙅 🚩
chirdeparag
Parag Chirde

Posted on July 15, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Event bus in Nuxt3
vue3 Event bus in Nuxt3

July 15, 2022