In Vue.js 3, the concept of an event bus, which was commonly used in Vue 2, can be implemented using a more modern and recommended approach involving the mitt library or the Vue 3 provide and inject features. The event bus is used to facilitate communication between components that do not have a direct parent-child relationship.

Using mitt Library for Event Bus in Vue 3

mitt is a tiny (~200 bytes) event emitter library that can be used to create an event bus in Vue 3. Here’s how you can set it up:

Install mitt:
First, install the mitt library using npm or yarn.

npm install mitt
# or
yarn add mitt

Create the Event Bus:
Create a separate file (e.g., eventBus.js) to initialize and export the event bus.

// eventBus.js
import mitt from 'mitt';
const emitter = mitt();
export default emitter;

Use the Event Bus in Components:
Parent Component: Where the event bus will be injected and provided to its children.


Child Component: Emit an event.


 

Sibling Component: Listen for the event.






Explanation

Installing mitt:

  1. You install the mitt library, which is a lightweight event emitter library suitable for creating an event bus in Vue 3.
    Creating the Event Bus:
  2. You create an eventBus.js file where you initialize the mitt instance and export it for use in other components.
  3. Parent Component:
    • The parent component imports the event bus and provides it to its child components using the provide function.
    • Child components can then use the inject function to access the event bus.
  4. Child Component:
    – The child component injects the event bus and uses the emit method to send an event named message with a payload.
    – When the button is clicked, the sendMessage method emits a message event with a string payload.
  5. Sibling Component:
    – The sibling component injects the event bus and sets up an event listener in the mounted lifecycle hook.
    – The on method is used to listen for the message event. When the event is received, the message is stored in the message data property.
    – The beforeUnmount lifecycle hook removes the event listener to prevent memory leaks.

This way, you can facilitate communication between sibling components using an event bus in Vue.js 3 with the help of the mitt library.

Need Help With Vue Development?

Work with our skilled Vue developers to accelerate your project and boost its performance.

Hire Vuejs Developers

Support On Demand!

Related Q&A