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

select the best presets to create full compatibility with all browsersselect

We know that the properties of the select tag in e...

How to use Navicat to operate MySQL

Table of contents Preface: 1. Introduction to Nav...

JavaScript countdown to close ads

Using Javascript to implement countdown to close ...

Example analysis of the usage of the new json field type in mysql5.7

This article uses an example to illustrate the us...

mysql row column conversion sample code

1. Demand We have three tables. We need to classi...

Solution to the data asymmetry problem between MySQL and Elasticsearch

Solution to the data asymmetry problem between My...

Teach you to create custom hooks in react

1. What are custom hooks Logic reuse Simply put, ...

CSS Reset style reset implementation example

Introduction: All browsers come with default styl...

Telnet is moved to busybox-extras in Alpine image

The telnet in the Alpine image has been moved to ...

iframe adaptive size implementation code

Page domain relationship: The main page a.html bel...

Linux service monitoring and operation and maintenance

Table of contents 1. Install the psutil package S...

Solution to MySQL replication failure caused by disk fullness

Table of contents Case scenario Solving the probl...

How to check the hard disk size and mount the hard disk in Linux

There are two types of hard disks in Linux: mount...