乐闻世界logo
搜索文章和话题

How to ` emit ` event out of ` setup ` method in vue3?

1个答案

1

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:

  1. Import defineComponent: First, ensure you use defineComponent to define the component for better TypeScript type inference.

  2. Accept the context parameter in the setup function: The setup function takes two parameters: props and context. The context object includes useful properties like emit for triggering events.

  3. Use context.emit to emit events: Emit custom events via context.emit and 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.

2024年10月27日 17:36 回复

你的答案