Scoped event bus with Vue.js
There are a number of excellent articles about creating global event buses with Vue.js. Recently I was using a global event bus similar to the one described here: Creating a Global Event Bus with Vue.js, it worked well when I was just dealing with just one Vue.js hierarchy (parent component with many children) per page. Then the requirements changed and I needed to have several parent components (with their corresponding children) per page.
Turns out that creating a scoped/local event bus is very easy! Here is a simple example.
The parent component:
// App.vue
<template>
<div id="app">
<child :eventBus="eventBus"></child>
</div>
</template>
<script>
import Vue from 'vue';
import Child from './Child.vue';
export default {
data: function () {
return {
eventBus: new Vue()
}
},
mounted() {
this.eventBus.$on("helloMessage", message => {
this.sayHello(message);
});
},
methods: {
sayHello: function(message) {
alert(message);
}
},
components: {
Child
}
}
</script>
The child component:
// Child.vue
<template>
<div>
<input v-model="message">
<a href="#" @click="hello()">
Click me!
</a>
</div>
</template>
<script>
export default {
data: function () {
return {
message: "Hello World"
}
},
methods: {
hello() {
this.eventBus.$emit("helloMessage", this.message);
}
},
props: {
"eventBus": Object,
}
}
</script>
And that’s it! Now you can pass events/messages from from one Vue.js component to another within a hierarchy.