Vue 3 Emits Event Declaration
In Vue 3, the emits option is used to declare custom events that a component can emit. By listing event names in the emits option, you explicitly specify which event types the component can use and define their parameter types.
Below is an example demonstrating how to declare custom events using the emits option in Vue 3:
export default {
name: 'MyComponent',
emits: ['my-event'],
// Other options for the component
}
In the code above, we use the emits option within the component's options object to declare a custom event that can be emitted. In this example, we declare a custom event named "my-event".
When the component needs to emit this custom event, it can use the $emit method:
this.$emit('my-event', eventData);
In the code above, we trigger the "my-event" using the $emit method and pass an eventData object as the argument.
Custom events can be listened to in templates via the v-on directive:
<template>
<button v-on:my-event="handleEvent"></button>
</template>
In the code above, we listen for the "my-event" using the v-on directive and bind a handler function named handleEvent to it.
It is important to note that the emits option serves not only for declaring custom event names but also for defining parameter types for events. For example, if a custom event requires passing parameters of specific types, you can declare them using an object format within the emits option:
export default {
name: 'MyComponent',
emits: {
'my-event': (eventData) => {
return typeof eventData === 'string';
}
},
// Other options for the component
}
In the code above, we declare the "my-event" using an object format and specify a validation function. This function checks whether the parameter passed to the "my-event" is of type string; only if it matches this condition will the event be triggered.