Javascript is required
·
1 min read
·
461 views

Vue Tip: Disable Attribute Inheritance

Vue Tip: Disable Attribute Inheritance Image

By default, parent scope attribute bindings that are not recognized as props will "fallthrough". This may not always be the desired behavior and, therefore, can be disabled.

Info

I wrote a dedicated tip about fallthrough attributes.

A short explanation of fallthrough attributes: When we have a single-root component, these bindings will be applied to the root element of the child component as standard HTML attributes.

This may only sometimes be the desired behavior when authoring a component that wraps a target element or another component.

By setting inheritAttrs to false, this default behavior can be disabled. The attributes are available via the $attrs instance property and can be explicitly bound to a non-root element using v-bind.

Let's take a look at an example. In this component, the <input> element that should receive the attributes is wrapped inside a <label> element. By default, the <label> element would inherit the attributes but we will fix that:

1<script>
2export default {
3  inheritAttrs: false,
4  props: ['label', 'value'],
5  emits: ['input'],
6}
7</script>
8
9<script setup>
10const count = ref(0)
11</script>
12
13<template>
14  <label>
15    <span>{{ label }}: {{ count }}</span>
16    <input v-bind="$attrs" v-bind:value="value" v-on:input="$emit('input', $event.target.value)" />
17  </label>
18</template>

By using inheritAttrs: false, the attributes do not "fallthrough" on the root node (<label>). We manually bound them to the <input> element via v-bind="$attrs".

As you can see in this example, it's absolutely valid to add two script blocks.

If you liked this Vue tip, follow me on Twitter to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:

I will never share any of your personal data. You can unsubscribe at any time.