DEV Community

emile2636
emile2636

Posted on

6 2

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.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Retry later
Retry later