Hello, Developers Hope you are doing well. In this tutorial, I am going to discuss vue custom events. Do you know what is vue custom events? If you don't know about vue custom events, don't worry I will help you to learn about it.
Actually, the general way of implementing a global event bus in Vue is just using the Vue object itself, nothing else of course. Many times we need a quick and very easy solution to pass data between Vue.js components. We can pass data from one vue component to another vue component using vue custom events.
Of course, there is Vuex for centralized state management in vue component. We can use vuex to manage the state in vue component, but in the tiny project, we can use vue custom events to do the same tasks.
So for an application with simple architecture and small-scale application. it’s enough to communicate between components using events. For this reason, we can create a quick solution and implement EventBus. EventBus permits us to emit an event in one component and listen for that event in another component or it would be the same component.
It is very simple to set up an event bus in Vue app. Just use this couple of line codes having it in your Vue component globally.
let Event = new Vue()
window.Event = Event;
Here we just created a vue object and to be assigned this object to the window object so that we can use it globally in Vue component.
Use of custom events without parameter:
export default {
data(){
return {
}
},
mounted() {
Event.$emit("vue_event_testing")
},
methods: {
test() {
Event.$on("vue_event_testing", () => {
console.log("Hello vue")
})
},
},
created(){
this.test()
}
}
Look here we use it in the same components. If you load this code having used it in your Vue component the output will be:
Use of custom events with parameters:
export default {
data(){
return {
name: "John"
}
},
mounted() {
Event.$emit("vue_event_testing", this.name)
},
methods: {
test() {
Event.$on("vue_event_testing", (name) => {
console.log(name)
})
}
},
created(){
this.test()
}
}
Read also : How to Pass Data from Blade to Vue Components
If you load this code the output will:
Have you understood? Here in this statement Event.$emit("vue_event_testing", this.name), the first option will be EVENT_NAME
name and the second parameter will be data. Hope you have understood.
Remember : You can use this Event.$on("vue_event_testing", (name) => { }) in another vue component to get the passing name data.
Hope this vue custom events tutorial can help you to learn new things.
#vue-js #events-bus #custom-events