DEV Community

emile2636
emile2636

Posted on

Create components with native HTML tags’ attributes by using “inheritAttrs” in Vue 2.4.0+

Scenario

When we want to pass some custom value to other components in Vue, passing “props” would be the first chose. However, when it comes to common attributes in HTML tags like autocomplete, maxlength, etc. We also want a “native HTML like” develop experience.

For example, we create a CustomInput component which contains input tag wrapped by a div with a class for styling.

// my custom input CustomInput
<template>
    <div class="myClass">
        <input attributes />
    </div>
</template>

// parent component import CustomInput 
<template>
    <div class="wrapper">
        ...
        <custom-input maxlength="5" autocomplete="hello" />
    </div>
</template>

What we want to do is that passing down attributes from parent component to CustomInput without using props.


Practice

By default, when attributes are passed down to a child component, the root HTML tag in child component will inherit those attributes.

// the output HTML from the above example
<div class="wrapper">
    <div class="myClass" maxlength="5" autocomplete="hello">
        <input />
    <div/>
<div/>

However, what we expected is that attributes can be inherited by <input/>.

Since Vue 2.4.0, there’s an option called “inheritAttrs”. By setting this option inheritAttrs: false, the default action will not be executed.

Finaly, we can use v-bind & $attrs to setup the attributes manually.

<script>
export default {
    inheritAttrs: false,
    data(){
        return {
            myLength:0,
        }
    },
    created(){
        this.myLength = this.$attrs.maxlength
    }
}
</script>
<template>
    <div class="myClass">
        <input v-bind="{...$attrs, maxlength:undefined}" />
    </div>
</template>

Besides of “Destructuring Assignment” the $attr object and attaching it by using v-bind , we can also replace the attribute’s value to undefined and manipulate it by ourself in data option for other usage.


It’s only a little trick for building custom components. Hope you are enjoy the article, and keep following me for the next sharing.

Top comments (0)