Vue Fallthrough Attributes

Vue Fallthrough Attributes

A "fallthrough attribute" is an attribute or event listener passed to a component, but not explicitly declared as a prop.

Common examples of these include class, style, and id attributes.

Vue automatically passes these attributes down to the child component's root element.


Attribute Inheritance

When a component renders a single root element, fallthrough attributes will be automatically added to it.

If you pass a class="large-btn" to <MyButton />, the internal <button> will inherit that class.

This saves you from having to define a prop for every possible HTML attribute.

Fallthrough Example:

<!-- Parent passing a class -->
<MyButton class="large" />

<!-- Child Template (MyButton.vue) --> <button>Click Me</button>

<!-- Rendered Output --> <button class="large">Click Me</button>


Class and Style Merging

What happens if the child component already has a class applied to its root element?

Vue is smart enough to merge the fallthrough classes with the existing classes!

They do not overwrite each other; they sit side-by-side perfectly.

Merging Example:

<!-- Parent passing a class -->
<MyButton class="extra-large" />

<!-- Child Template --> <button class="btn-primary">Click Me</button>

<!-- Rendered Output --> <button class="btn-primary extra-large">Click Me</button>


Disabling Attribute Inheritance

Sometimes you do not want the root element to inherit attributes.

You can disable this default behavior by setting inheritAttrs: false in the component's options.

You can then manually bind the attributes to a different internal element using v-bind="$attrs".


Exercise 1 of 2

?

What is a fallthrough attribute in Vue?

Exercise 2 of 2

?

If a parent passes a class to a child component that already has a class on its root element, what happens?