Sometimes, we want to programmatically bind custom events for dynamic components in Vue.js.
In this article, we’ll look at how to programmatically bind custom events for dynamic components in Vue.js.
How to programmatically bind custom events for dynamic components in Vue.js?
To programmatically bind custom events for dynamic components in Vue.js, we can use the this.$on
method.
For instance, we write
<script>
export default {
//...
created() {
const EVENTS = [
{ name: "my-event1", callback: () => console.log("event1") },
{ name: "my-event2", callback: () => console.log("event2") },
{ name: "my-event3", callback: () => console.log("event3") },
];
for (const e of EVENTS) {
this.$on(e.name, e.callback);
}
this.$on(["click", "keyup"], (e) => {
console.log("event", e);
});
},
};
</script>
to call this.$on
with one event name and a event handler callback as did in the for-of loop.
We can also call this.$on
with an array of event names and an event handler callback for all the events.
Conclusion
To programmatically bind custom events for dynamic components in Vue.js, we can use the this.$on
method.