In Vue 3, when using the Composition API, the setup method is a core concept. Within this method, we can define reactive data, computed properties, and functions. When emitting events from the setup function, we utilize context.emit.
Here are the specific steps and examples:
-
Import
defineComponent: First, ensure you usedefineComponentto define the component for better TypeScript type inference. -
Accept the
contextparameter in thesetupfunction: Thesetupfunction takes two parameters:propsandcontext. Thecontextobject includes useful properties likeemitfor triggering events. -
Use
context.emitto emit events: Emit custom events viacontext.emitand pass the necessary data as parameters.
Here is a specific example:
vue<template> <button @click="sendEvent">Click me to emit an event</button> </template> <script> import { defineComponent } from 'vue'; export default defineComponent({ setup(props, { emit }) { // Define a function to trigger the event const sendEvent = () => { emit('custom-event', { message: 'Hello from setup!' }); }; // Expose the function to the template return { sendEvent }; } }); </script>
In this example, we create a button that triggers the sendEvent function when clicked. This function uses emit to emit a custom event named custom-event with the data { message: 'Hello from setup!' }. In the parent component, you can listen for this event:
vue<template> <ChildComponent @custom-event="handleEvent" /> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { methods: { handleEvent(eventData) { console.log('Event triggered:', eventData.message); } } } </script>
When the event is triggered, you can see the passed message in the console. This demonstrates how to emit events from the setup method in Vue 3.