Fallthrough Attributes in Vue
Fallthrough attributes in Vue allow you to pass attributes or event listeners to a component without explicitly declaring them in its props
or emits
. This provides flexibility and convenience when working with components.
Automatic Attribute Inheritance
In a component with a single root element, attributes not declared in props
or emits
are automatically added to the root element. For example:
<MyButton class="large" />
In the MyButton
component:
<!-- MyButton component template -->
<button>click me</button>
This results in the rendered DOM:
<button class="large">click me</button>
class
and style
Merging
class
and style
MergingIf the component's root element already has class
or style
attributes, they will be merged with inherited values:
<!-- MyButton component template -->
<button class="btn">click me</button>
With the parent:
<MyButton class="large" />
The rendered DOM becomes:
<button class="btn large">click me</button>
Inheriting v-on
Event Listeners
v-on
Event ListenersThe same fallthrough behavior applies to v-on
event listeners:
<MyButton @click="onClick" />
The click
event listener will be added to the root element of MyButton
.
Nested Component Inheritance
If a component renders another component as its root node, fallthrough attributes are forwarded:
<!-- MyButton component template -->
<BaseButton />
Attributes received by MyButton
are forwarded to BaseButton
.
Disabling Attribute Inheritance
To disable automatic attribute inheritance, set inheritAttrs: false
in the component's options:
<script setup>
defineOptions({
inheritAttrs: false
});
</script>
Now, you can access fallthrough attributes using $attrs
:
<span>Fallthrough attributes: {{ $attrs }}</span>
Last updated