In Vue Js we have essentially three ways of making unrelated components communicate with each other:
Vuex
Pinia
Event Bus
On the official documentation, we can read:
In most circumstances, using a global event bus for communicating between components is discouraged. While it is often the simplest solution in the short term, it almost invariably proves to be a maintenance headache in the long term.
So generally in the long run it is better to use Vuex. Also in the official documentation, you can see how the Event Bus implementation has changed from Vue 2 to Vue 3.
In this tutorial, we will use the Vite build tool to scaffold the project.
# npm 6.x
npm init vite@latest vue-event-bus-1 --template vue
# npm 7+, extra double-dash is needed:
npm init vite@latest vue-event-bus-1 -- --template vue
Then we need to install an external library implementing the event emitter interface, in this case, mitt.
npm install --save mitt
The project consists of two simple components, FirstComponent.vue, and SecondComponent.vue when we click on the emit event button in SecondComponent.vue String to change in FirstComponent.vue becomes String changed thanks to the Event Bus
In main.js we create an instance of mitt which is used globally
import { ***createApp ***} from 'vue'
import mitt from 'mitt'
import App from './App.vue'
const emitter = mitt()
const app = ***createApp***(App)
app.config.globalProperties.emitter = emitter
app.mount('#app')
Now we can access the emitter globally, so in FirstComponent.vue we subscribe to the event emitted by SecondComponent.vue.
Let’s take a look at FirstComponent.vue
<script>
export default {
data: function () {
return {
testEvent: 'String to change'
}
},
created (){
this.emitter.on('my-event', (evt) => {
this.testEvent = evt.eventContent;
})
}
}
</script>
Now in SecondComponent.vue, let’s emit the event.
<template>
<div style="border: 1px solid black;">
<h1>Second Component</h1>
<button v-on:click="emitMyEvent">Emit Event</button>
</div>
</template>
<script>
export default {
methods: {
emitMyEvent() {
this.emitter.emit('my-event', {'eventContent': 'String changed'})
}
}
}
</script>
You can find the code of this tutorial on github: https://github.com/CertosinoLab/mediumarticles/tree/vue-event-bus-1
Thank you for reading