emits
Option Vue 3 now offers an emits
option, similar to the existing props
option. This option can be used to define the events that a component can emit to its parent.
In Vue 2, you can define the props that a component receives, but you can't declare which events it can emit:
<template> <div> <p>{{ text }}</p> <button v-on:click="$emit('accepted')">OK</button> </div> </template> <script> export default { props: ['text'] } </script>
Similar to props, the events that the component emits can now be defined with the emits
option:
<template> <div> <p>{{ text }}</p> <button v-on:click="$emit('accepted')">OK</button> </div> </template> <script> export default { props: ['text'], emits: ['accepted'] } </script>
The option also accepts an object, which allows the developer to define validators for the arguments that are passed with the emitted event, similar to validators in props
definitions.
For more information on this, please read the API documentation for this feature.
It is highly recommended that you document all the events emitted by each of your components using emits
.
This is especially important because of the removal of the .native
modifier. Any listeners for events that aren't declared with emits
will now be included in the component's $attrs
, which by default will be bound to the component's root node.
For components that re-emit native events to their parent, this would now lead to two events being fired:
<template> <button v-on:click="$emit('click', $event)">OK</button> </template> <script> export default { emits: [] // without declared event } </script>
When a parent listens for the click
event on the component:
<my-button v-on:click="handleClick"></my-button>
it would now be triggered twice:
$emit()
.Here you have two options:
click
event. This is useful if you actually do add some logic to that event handler in <my-button>
..native
. Suitable when you really only re-emit the event anyway.
© 2013–present Yuxi Evan You
Licensed under the MIT License.
https://v3.vuejs.org/guide/migration/emits-option.html