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

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.
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.
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.
