Vue3 inheritAttrs Property
In Vue 3,inheritAttrs is a component option that determines whether non-prop attributes (i.e., attributes not explicitly defined as props) passed from the parent component to the child component should be inherited onto the child component's root element.
By default,inheritAttrs has a value of true, which means all non-prop attributes passed by the parent component are automatically bound to the child component's root element. If you want to manually control the inheritance behavior of these attributes, you can set inheritAttrs to false.
How to Understand inheritAttrs?
Imagine you have a component MyButtonthat receives a label as a prop, and you want the parent component to be able to pass some extra attributes, such as class or style. By default, these extra attributes are bound directly to MyButton 's root element (usually a element).
Example
// MyButton.vue
<
template
<
button:
class
=
"$attrs.class"
{
{
label
}
}
button
template
<
script
export
default
{
props:
[
'label'
]
,
inheritAttrs
:
true
}
script
In this example, if the parent component passes a class attribute, it is automatically bound to MyButton 's element in the page.
inheritAttrs: false The Role of
If you do not want these non-prop attributes to be automatically bound to the root element, you can set inheritAttrs to false. This way, you can manually decide how these attributes should be handled.
Example
// MyButton.vue
<
template
<
div
<
button
{
{
label
}
}
button
<span v
bind
=
"$attrs"
Additional Attributes
span
div
template
<
script
export
default
{
props:
[
'label'
]
,
inheritAttrs
:
false
}
script
In this example, the non-prop attributes are not bound to the element, but are instead bound to the element. You can use v-bind="$attrs" to bind the attributes to any element you want.
Use Cases
-
Custom Attribute Binding: When you do not want non-prop attributes to be automatically bound to the root element, you can disable
inheritAttrsand manually control how these attributes are bound. -
Avoid Attribute Conflicts: In some cases, automatically bound non-prop attributes may conflict with the child component's attributes. Disabling
inheritAttrscan avoid this problem. -
Advanced Component Development: When developing complex components, you may need more flexible handling of attribute passing and binding.
inheritAttrs: falseprovides this flexibility.
Vue3 Options API