When a component returns a single root node, non-prop attributes will automatically be added to the root node's attributes. For example, in the instance of a date-picker component:
app.component('date-picker', {
template: `
<div class="date-picker">
<input type="datetime" />
</div>
`
})
In the event we need to define the status of the date-picker component via a data-status
property, it will be applied to the root node (i.e., div.date-picker
).
<!-- Date-picker component with a non-prop attribute -->
<date-picker data-status="activated"></date-picker>
<!-- Rendered date-picker component -->
<div class="date-picker" data-status="activated">
<input type="datetime" />
</div>
Disabling Attribute Inheritance
If you do not want a component to automatically inherit attributes, you can set inheritAttrs: false
in the component's options.
The common scenario for disabling an attribute inheritance is when attributes need to be applied to other elements besides the root node.
By setting the inheritAttrs
option to false
, you can control to apply to other elements attributes to use the component's $attrs
property, which includes all attributes not included to component props
and emits
properties (e.g., class
, style
, v-on
listeners, etc.).
Using our date-picker component example from the previous section, in the event we need to apply all non-prop attributes to the input
element rather than the root div
element, this can be accomplished by using the v-bind
shortcut.
app.component('date-picker', {
inheritAttrs: false,
template: `
<div class="date-picker">
<input type="datetime" v-bind="$attrs" />
</div>
`
})
With this new configuration, our data-status
attribute will be applied to our input
element!
<!-- Date-picker component with a non-prop attribute -->
<date-picker data-status="activated"></date-picker>
<!-- Rendered date-picker component -->
<div class="date-picker">
<input type="datetime" data-status="activated" />
</div>