Vue encapsulation component tool $attrs, $listeners usage

Vue encapsulation component tool $attrs, $listeners usage

Preface

When multi-level component nesting requires data transfer, the commonly used method is through vuex. But just passing data without any intermediate processing and using vuex for processing is a bit of an overkill. So there are two attributes, $attrs and $listeners, which are usually used together with inheritAttrs.

$attrs

The properties passed from the parent component to the custom child component will be automatically set to the outermost tag inside the child component if there is no prop receiver. If it is a class and style, the class and style of the outermost tag will be merged.

If the child component does not want to inherit the non-prop attributes passed in by the parent component, you can use inheritAttrs to disable inheritance, and then set the external non-prop attributes passed in to the desired tag through v-bind="$attrs", but this will not change the class and style.

inheritAttrs attribute official website link

2.4.0 New

Type: boolean

Default value: true

detailed:

By default, parent-scoped attribute bindings that are not recognized as props will "fall back" and be applied as normal HTML attributes on the child component's root element. When writing components that wrap a target element or another component, this may not always be the expected behavior. By setting inheritAttrs to false, this default behavior will be removed. These attributes can be made effective through the instance property $attrs (also new in 2.4), and can be explicitly bound to non-root elements through v-bind.

Note: This option does not affect class and style bindings.

example:

Parent Component

<template>
  <my-input
      required
      placeholder="Please enter content"
      type="text"
      class="theme-dark"
  />
</template>

<script>
import MyInput from './child'
export default {
  name: 'parent',
  components:
    MyInput
  }
}
</script>

Subcomponents

<template>
  <div>
    <input
        v-bind="$attrs"
        class="form-control"
    />
  </div>
</template>

<script>
export default {
  name: 'MyInput',
  inheritAttrs: false
}
</script>

The child component does not accept the value passed from the parent component, nor does it bind, but with the attribute v-bind="$attrs", it will automatically accept and bind

inheritAttrs: false

inheritAttrs: true

$listeners (official explanation)

listeners: Contains v-on event listeners in the parent scope (without the .native modifier). It can be passed into inner components via v-on="$listeners" - very useful when creating higher level components.

First, let's look at the code: Here we only take the focus and input events as examples.

// Parent component <template>
  <my-input
      required
      placeholder
      class="theme-dark"
      @focue="onFocus"
      @input="onInput"
  >
  </my-input>
</template>
<script>
import MyInput from './child'
export default {
  components:
    MyInput
  },
  methods: {
    onFocus (e) {
      console.log(e.target.value)
    },
    onInput (e) {
      console.log(e.target.value)
    }
  }
}
</script>
// Subcomponent <template>
  <div>
    <input
        type="text"
        v-bind="$attrs"
        class="form-control"
        @focus="$emit('focus', $event)"
        @input="$emit('input', $event)"
    />
  </div>
</template>

<script>
export default {
  name: 'MyInput',
  inheritAttrs: false
}
</script>

It is very troublesome to bind native events in this way. Every native event needs to be bound, but using v-on="$listeners" will save a lot of trouble.

 <input
        type="text"
        v-bind="$attrs"
        class="form-control"
+ v-on="$listeners"
- @focus="$emit('focus', $event)"
- @input="$emit('input', $event)"
    />

This one line of code can solve the problem of binding all native events

Usage scenarios

Used when components pass values: Grandfather passes values ​​to the father component, and the father component obtains all attributes that are not in the father's props through $attrs. The father component binds $attrs and $listeners to the grandchild component so that the grandchild component can obtain the value passed by the grandfather and call the method defined in the grandfather;

Used for secondary packaging of some UI libraries: For example, when the components in element-ui cannot meet your own usage scenarios, they will be secondary packaged, but you want to retain their own properties and methods. At this time, $attrs and $listners are a perfect solution.

Summarize

This is the end of this article about the use of $attrs and $listeners, a powerful tool for Vue encapsulation components. For more information on the use of $attrs and $listeners of Vue encapsulation components, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Let's talk briefly about $attrs and $listeners of vue2.x
  • The use and difference of vue $attrs and $listeners
  • Detailed explanation of how to use $props, $attrs and $listeners in Vue
  • Tutorial on using $attrs and $listeners in Vue
  • Vue $attrs & inheritAttr to achieve button disabled effect case
  • Analysis of the implementation principle of $attrs and $listeners in Vue component communication
  • A comprehensive analysis of the use of vue $attrs

<<:  7 major elements of web page redesign Share the 7 major elements of web page redesign

>>:  Linux user script creation/guessing game/network card traffic monitoring introduction

Recommend

How to reduce the root directory of XFS partition format in Linux

Table of contents Preface System environment Curr...

Detailed explanation of basic syntax and data types of JavaScript

Table of contents Importing JavaScript 1. Interna...

Detailed explanation of how to synchronize data from MySQL to Elasticsearch

Table of contents 1. Synchronization Principle 2....

How to use less in WeChat applet (optimal method)

Preface I am used to writing less/sass, but now I...

Solution to the MySQL server has gone away error

MySQL server has gone away issue in PHP 1. Backgr...

Use elasticsearch to delete index data regularly

1. Sometimes we use ES Due to limited resources o...

Vue implements nested routing method example

1. Nested routing is also called sub-routing. In ...

Use Vue3 to implement a component that can be called with js

Table of contents Preface 1. Conventional Vue com...

A summary of some of the places where I spent time on TypeScript

Record some of the places where you spent time on...

A pitfall and solution of using fileReader

Table of contents A pitfall about fileReader File...

CentOS 7 Forgot Password Solution Process Diagram

need Whether it is a Windows system or a Linux sy...

jQuery achieves the effect of advertisement scrolling up and down

This article shares the specific code of jQuery t...

Unicode signature BOM (Byte Order Mark) issue for UTF-8 files

I recently encountered a strange thing when debug...

Summary of the application of transition components in Vue projects

​Transtion in vue is an animation transition enca...