Vue3 inheritAttrs Property
In Vue3,inheritAttrsis a component option that determines whether non-prop attributes (i.e., attributes that are not explicitly defined as props) passed from the parent component to the child component should be inherited onto the root element of the child component.
By default,inheritAttrsthe value oftrue, which means that all non-prop attributes passed by the parent component will be automatically bound to the root element of the child component.inheritAttrsset tofalse。
How to understandinheritAttrs?
Imagine you have a componentMyButton, it receives alabelas a prop, and you want the parent component to be able to pass some additional attributes, such asclassorstyle. By default, these additional attributes will be directly bound toMyButtonthe root element of (usually a<button>element).
Example
<template>
<button :class="$attrs.class"> {{ label }} </button>
</template>
<script>
export default {
props: ['label'],
inheritAttrs: true
}
</script>
In this example, if the parent component passes aclassattribute, it will be automatically bound toMyButtonof<button>element.
inheritAttrs: falseThe role of
If you do not want these non-prop attributes to be automatically bound to the root element, you can setinheritAttrsset tofalse. This way, you can manually decide how these attributes should be handled.
Example
<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, non-prop attributes will not be bound to<button>element, but are instead bound to<span>element. You can usev-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
inheritAttrs, and manually control how these attributes are bound.Avoiding 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 flexibility in handling the passing and binding of attributes.
inheritAttrs: falseprovides this flexibility.
Other extensions
Vue3 Options API