EventBus is a way of communication between components in Vue. The common ways of communication between parent and child components are through emit and props. However, if there is a need for cross-component communication or communication between sibling components, using EventBus or Vuex can avoid the repetition of props and emit. Vuex is suitable for medium to large projects, managing globally shared states. EventBus is more suitable for small projects with less complex events.
Usage:
EventBus is actually just an instance of Vue. It can be used to trigger events and listen to events for communication and parameter passing. The main methods are as follows:
- $on: Register a listener
- $once: Listen to an event only once
- $off: Cancel a listener
- $emit: Send an event
Usually, listeners are registered in the created hook of a page, and they are canceled when the component is destroyed.
Creating an EventBus:
It is actually creating an instance of Vue.
import Vue from 'vue';
// Use Event Bus
const bus = new Vue();
export default bus;
Import it in the components where events need to be sent and received.
import bus from '../common/bus';
Listening:
In the created hook of the component where listening is needed, use bus to listen.
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 cause multiple triggers of the listener. Therefore, we need to use $off to cancel the binding. Usually, it is bound in the beforeDestroy() or destroyed() hooks.
// Remove the listener for a specific event
bus.$off('getSomething')
// Remove all listeners
bus.$off()