Skip to the workspace
Pebellslearn by building
Templates  ›  Capstone Project

Attribute Inheritance

Attribute Inheritance 14 minAttributes and listeners a component does not declare as props or emits fall through to its single root element.

vue / Attribute Inheritance

Explore each scene at your own pace.

01 · The rule

The rule

Attribute Inheritance

Shelf gets a SearchBox component. On one page the parent writes <SearchBox class="wide" placeholder="Find a book" />. SearchBox never declared class or placeholder as props, yet something happens to them. Knowing where they go saves an afternoon of "why is my input not wide?"

The rule

Undeclared attributes fall through to the single root element.

Anything a parent passes that the child did not claim with defineProps or defineEmits is a fallthrough attribute. That includes class, style, id, placeholder, and v-on listeners such as @click. If the component renders one root element, Vue adds them to it automatically.

<!-- SearchBox.vue, first version -->
<template>
  <label class="search">
    Search
    <input type="search" />
  </label>
</template>

With <SearchBox class="wide" placeholder="Find a book" />, the root label becomes class="search wide" placeholder="Find a book". The class merges nicely with the existing one. The placeholder, sadly, sits on the label, where it does nothing.

To choose the destination yourself, switch off automatic inheritance and bind $attrs where you want it:

<!-- SearchBox.vue, fixed -->
<script setup>
defineOptions({ inheritAttrs: false })
</script>

<template>
  <label class="search">
    Search
    <input type="search" v-bind="$attrs" />
  </label>
</template>

Now placeholder, class and any listener land on the input. In script code the same object is available through useAttrs() from vue.

Several root elements: if a template has more than one top-level element, Vue cannot guess which should receive the attributes. It adds them nowhere and warns, unless you bind $attrs explicitly on one of them.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.