$attrs and $listeners (vue2&&vue3)

Table of Contents

Transparent transmission Attributes

Attributes inheritance?

Merging class and style

v-on listener inheritance

Deep component inheritance

Disable Attributes inheritance

Attributes inheritance for multi-root nodes

vue2 $attrs and $listeners

$attrs Concept Description

$attrs case

$listeners Concept Description

$listeners case

vue3 $attrs and $listeners

Usage of attrs in template

When there is only 1 root element

When there are 2 root elements

$listeners deprecated

Usage of attrs in js

Options API

Syntax of Composition API 3.0

Syntax of Composition API 3.2

Summarize

Remove $listeners

Overview

2.x syntax

3.x syntax

$attrs contains class & amp; style

Overview

2.x Behavior

3.x Behavior


(1) $props: The props object received by the current component. The Vue instance delegates access to its props object properties.

(2) $attrs: Contains attribute bindings (except class and style) that are not recognized (and obtained) as props in the parent scope.

(3) $listeners: Contains v-on event listeners in the parent scope (without .native modifier). He can pass v-on=”listeners” into internal components

Fallthrough Attributes

Transparent transmission of Attributes refers to attributes and event handlers that are passed in from the parent component and are not declared as props by the child component or as component custom events.

Attributes inheritance?

“Transparent attributes” refer to attributes that are passed to a component but are not declared as props or emits or v-on event listeners by the component. The most common examples are class, style and id.

When a component is rendered with a single element as the root, the transparent attributes are automatically added to the root element. For example, if we have a component, its template looks like this:

<!-- Template for <MyButton> -->
<button>click me</button>

A parent component uses this component and passes in class:

<MyButton class="large" />

The final rendered DOM result is:

<button class="large">click me</button>

Here, does not declare class as a prop it accepts, so class is regarded as a pass-through attribute and is automatically passed through. Passed to the root element of .

Merging of class and style

If a child component’s root element already has a class or style attribute, it will be merged with the value inherited from the parent component. If we change the template of the previous component to this:

<!-- Template for <MyButton> -->
<button class="btn">click me</button>

Then the final rendered DOM result will become:

<button class="btn large">click me</button>

v-on Listener inheritance

The same rules apply to v-on event listeners

<MyButton @click="onClick" />

The click listener will be added to the root element of , which is the native