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.
Step-by-Step Guide
1. Understanding Event Emission in Vue.js:
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.
2. Setting Up 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';
<em>// Define the events the component can emit</em>
const emits = defineEmits(['getCallback']);
<em>// Emit the event</em>
emits('getCallback');
</script>
<template>
<div>
<button @click="emits('getCallback')">Trigger Event</button>
</div>
</template>
Here’s what’s happening:
- defineEmits: This function is used to declare the events that the component can emit.
- emits: The event is emitted using the
emits()
function, and it can be triggered within the script or through user interaction (like a button click).
3. Listening for the Event in the Parent Component:
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=”getUserCallBack”: The event is being listened to in the parent component using the kebab-case version of the event name (
get-callback
). - getUserCallBack: This method is triggered whenever the event is emitted from the child component, logging a message to the console.
Conclusion:
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.