Vue.js offers a simple and effective way to communicate between components using events. Emitting custom events and responding to them is crucial in building dynamic and reactive applications. In this guide, we’ll cover how to emit and handle events in Vue 3 using the defineEmits function and the Composition API.
In Vue.js, components can communicate through custom events. The child component can emit an event, which the parent component listens to and responds to. This is especially useful when you need to trigger a function in the parent based on actions happening in the child component.
To emit an event in Vue 3 using the Composition API, you need to use the defineEmits function. Let’s see how this works:
<script setup>
import { defineEmits } from 'vue';
// Define the events the component can emit
const emits = defineEmits(['getCallback']);
// Emit the event
emits('getCallback');
</script>
<template>
<div>
<button @click="emits('getCallback')">Trigger Event</button>
</div>
</template>
Here’s what’s happening:
emits() function, and it can be triggered within the script or through user interaction (like a button click).Now that the child component emits the getCallback event, let’s see how the parent component listens and responds to it:
<template>
<div>
<AddNewStation @get-callback="getUserCallBack" />
</div>
</template>
<script setup>
const getUserCallBack = () => {
console.log('Event received: Callback triggered');
};
</script>
In this example:
get-callback).Using events in Vue.js is an effective way to manage parent-child component communication. By leveraging the defineEmits function in Vue 3, you can create clear and maintainable code for emitting and handling custom events. Whether you’re building small components or large-scale applications, mastering event handling is key to building dynamic and interactive user experiences.