steffenstein.com

How to solve Extraneous non-props attributes in Vue Js

Extraneous non-props attributes (id) v-if

2024-02-14

There is very well written blog post about how to solve the problem of Extraneous non-props attributes in Vue Js. Blogpost

How to solve it in VUE3 with the setup function

The trick is to use the useAttrs function within the Composition API to access and bind all attributes passed to a component that are not recognized as props. This is especially useful for forwarding attributes to child components or base elements within your component, maintaining reactivity and ensuring that any attribute changes are reflected in the child component or element.

<script setup lang="ts">
import { useAttrs } from 'vue';

const attrs = useAttrs();
/// ... code
</script>

<template>
  <input
    v-if="!inputWithText"
    v-bind="attrs"
  />
    <label
      v-bind="attrs"
      v-if="inputWithText"
    >
      {{ inputText }}
      <input type="text" class="grow" placeholder="Daisy" />
    </label>
</template>

Why this matters

By using v-bind="attrs" in the template, we dynamically bind all attributes that are not explicitly defined as props in the component. This is particularly useful for passing down class, style, or custom attribute bindings.

Avatar of Steffen Stein

Hi, my name is Steffen 👋 I'm a webdeveloper from Cologne, Germany 🇩🇪 Coding abroad and traveling the world 🌎 ✈️