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

nchuuu
nchuuu
Nov 4 · 2 min read
Photo by Safar Safarov on Unsplash

Scenario

When we want to pass some custom values 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” coding experience.

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

Pass down some attributes without using props.

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.

Manipulating “maxlength” to “myLength” in data option by ourself

Besides of “Destructuring Assignment” within the $attr object and attaching it by usingv-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.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade