Sometimes, we want to add an event bus with Vue.js 3.
In this article, we’ll look at how to add an event bus with Vue.js 3.
How to add an event bus with Vue.js 3?
To add an event bus with Vue.js 3, we can use the mitt
package.
To install it, we run
npm install --save mitt
Then we use it by writing
import { createApp } from "vue";
import App from "./App.vue";
import mitt from "mitt";
const emitter = mitt();
const app = createApp(App);
app.config.globalProperties.emitter = emitter;
app.mount("#app");
in our app’s entry point file.
We make emitter
available to all components with
app.config.globalProperties.emitter = emitter;
Then we use it by writing
<template>
<header>
<button @click="toggleSidebar">toggle</button>
</header>
</template>
<script>
export default {
data() {
return {
sidebarOpen: true,
};
},
methods: {
toggleSidebar() {
this.sidebarOpen = !this.sidebarOpen;
this.emitter.emit("toggle-sidebar", this.sidebarOpen);
},
},
};
</script>
We call this.emitter.emit
to emit the toggle-sidebar
event.
Then in another component, we write
<template>
<aside class="sidebar" :class="{ 'sidebar--toggled': !isOpen }">...</aside>
</template>
<script>
export default {
name: "sidebar",
data() {
return {
isOpen: true,
};
},
mounted() {
this.emitter.on("toggle-sidebar", (isOpen) => {
this.isOpen = isOpen;
});
},
};
</script>
to call this.emitter.on
to listen to the toggle-siderbar
event and get the value in the 2nd argument of emit
from the isOpen
parameter in the callback.
Conclusion
To add an event bus with Vue.js 3, we can use the mitt
package.