In Vue 3, using the <script setup> syntax, a common approach to emit events from child components to parent components is to use the defineEmits function to declare the events that can be emitted, and then use it to emit events. Below are the specific steps and examples:
Steps:
-
Declare the events that can be emitted in the child component:
- Use
defineEmitsto declare the events that can be emitted.
- Use
-
Trigger events in the child component:
- In appropriate places, such as within methods or lifecycle hooks, use the emitter to emit events and pass data to the parent component.
-
Listen for the event in the parent component:
- In the parent component's template, use
v-onor its shorthand@to listen for events emitted by the child component and define the corresponding handling function.
- In the parent component's template, use
Example:
Child Component (ChildComponent.vue)
vue<script setup> // Import defineEmits import { defineEmits } from 'vue'; // Declare the events that can be emitted; here, an event named 'update' is declared const emit = defineEmits(['update']); // Define a method to trigger the event at appropriate times const updateParent = (data) => { emit('update', data); }; </script> <template> <button @click="updateParent('Hello from Child')">Update Parent</button> </template>
Parent Component (ParentComponent.vue)
vue<template> <!-- Listen for the 'update' event emitted by the child component and define the handling function handleUpdate --> <ChildComponent @update="handleUpdate" /> </template> <script setup> import { ref } from 'vue'; import ChildComponent from './ChildComponent.vue'; // Define the method to handle data received from the child component const handleUpdate = (data) => { console.log('Received data from child:', data); }; </script>
In this example, ChildComponent has a button that, when clicked by the user, emits an event named 'update' through the emitter and sends some data (in this case, the string 'Hello from Child'). ParentComponent listens for this update event and executes the handleUpdate method when the event is triggered, which can receive and process the data sent from the child component.
Thus, you can emit events from child components to parent components in Vue 3 components using the <script setup> syntax.