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

The unreasonable MaxIdleConns of MySQL will cause short connections

1 Background Recently, some performance issues ha...

MySQL Order By Multi-Field Sorting Rules Code Example

Say it in advance On a whim, I want to know what ...

JavaScript counts the number of times a character appears

This article example shares the specific code of ...

Nginx routing forwarding and reverse proxy location configuration implementation

Three ways to configure Nginx The first method di...

How to set Nginx to forward the domain name to the specified port

Enter /usr/local/nginx/conf sudo cd /usr/local/ng...

MySQL 5.7 Common Data Types

——Notes from "MySQL in Simple Terms (Second ...

Steps to install MySQL 8.0.23 under Centos7 (beginner level)

First, let me briefly introduce what MySQL is; In...

Implementation of CSS dynamic height transition animation effect

This question originated from a message on Nugget...

Meta declaration annotation steps

Meta declaration annotation steps: 1. Sort out all...

Meta viewport makes the web page full screen display control on iPhone

In desperation, I suddenly thought, how is the Sin...

Detailed explanation of count without filter conditions in MySQL

count(*) accomplish 1. MyISAM: Stores the total n...

Steps to configure IIS10 under Win10 and support debugging ASP programs

Microsoft IIS IIS (Internet Information Server) i...

Solution for FileZilla 425 Unable to connect to FTP (Alibaba Cloud Server)

Alibaba Cloud Server cannot connect to FTP FileZi...