EventBus is a way to communicate between components in Vue. The common ways for parent-child component communication are emit and props. However, if you need to communicate between components that are not directly related or between sibling components, using EventBus or Vuex can avoid the repetition of props and emit. Vuex is suitable for medium to large projects to manage globally shared states. EventBus is more suitable for small projects with less complex events.
Usage#
EventBus is actually just an instance of Vue. You can use the event triggering and listening methods of this instance to achieve communication and parameter passing. The main methods are as follows:
- $on: Register a listener
- $once: Listen once
- $off: Cancel a listener
- $emit: Send an event
Usually, you register the listener in the created hook of the page and cancel the listener when the component is destroyed.
Creating an EventBus#
Basically, you just need to create an instance of Vue.
import Vue from 'vue';
// Use Event Bus
const bus = new Vue();
export default bus;
Import it in the components where you need to send and receive events.
import bus from '../common/bus';
Listening#
In the component where you need to listen, use bus to listen in the created hook.
created() {
bus.$on('getSomething', target => {
console.log(target);
});
}
Sending an Event#
methods: {
// Emit the event
doSomething(target) {
bus.$emit("getSomething", target);
}
}
Canceling a Listener#
EventBus listeners do not automatically close, which can lead to multiple triggers of the listener. Therefore, we need to use $off to cancel the binding. Usually, you bind it in the beforeDestroy() or destroyed() hook.
// Remove the listener for the event
bus.$off('getSomething')
// Remove all listeners
bus.$off()