Transfer data between Components – VueJS Event Bus
VueJS provides a simple and elegant way to transfer data between components using an event bus. An event bus is an instance of Vue that can emit events and listen to them, allowing different components to communicate with each other.
To create an event bus in VueJS, you can simply do the following:
const bus = new Vue()
Now, you can use this event bus to emit and listen to events within your components. Here’s an example of how to use the event bus to transfer data between two components:
Component A
export default {
methods: {
sendDataToComponentB() {
bus.$emit('data-updated', { message: 'Hello from Component A' })
}
}
}
Component B
export default {
mounted() {
bus.$on('data-updated', (data) => {
console.log(data.message) // Output: Hello from Component A
})
}
}
In this example, when sendDataToComponentB method is called in Component A, it emits a ‘data-updated’ event with the message payload. Component B listens to this event and logs the message to the console. This allows Component A to communicate with Component B and transfer data between them using the event bus.
Using an event bus to transfer data between components is a powerful and flexible way to manage state and communication in your VueJS application. It allows you to decouple components and improve the reusability and maintainability of your code.
With the event bus pattern, you can easily transfer complex data structures, trigger actions in different components, and create a more modular and organized application architecture.
Overall, the event bus in VueJS provides a simple yet effective way to transfer data between components and enables seamless communication and collaboration within your application.