炫意html5
最早CSS3和HTML5移动技术网站之一

[Vue 3] 迁移指南 – emits Option

# emits Option


新增

# Overview

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.

# 2.x Behavior

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>

# 3.x Behavior

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.

# Migration Strategy

It is highly recommended that you document all of 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.

# Example

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:

  • Once from $emit().
  • Once from a native event listener applied to the root element.

Here you have two options:

  1. Properly declare the click event. This is useful if you actually do add some logic to that event handler in <my-button>.
  2. Remove the re-emitting of the event, since the parent can now listen for the native event easily, without adding .native. Suitable when you really only re-emit the event anyway.

# See also

  • Relevant RFC
  • Migration guide – .native modifier removed
  • Migration guide – $listeners removed
  • Migration guide – $attrs includes class & style
  • Migration guide – Changes in the Render Functions API

炫意HTML5 » [Vue 3] 迁移指南 – emits Option

CSS3教程HTML5教程