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

If 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:

Inheriting v-on Event Listeners

The same fallthrough behavior applies to v-on event listeners:

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:

Attributes received by MyButton are forwarded to BaseButton.

Disabling Attribute Inheritance

To disable automatic attribute inheritance, set inheritAttrs: false in the component's options:

Now, you can access fallthrough attributes using $attrs:

Last updated