0

Allowance of any attributes for components creates problems for me.

Playground

For example taking this:

<script setup lang="ts">
import { ref } from 'vue';
import Checkbox from './Checkbox.vue';

const value = ref(false);
</script>

<template>
  <div>{{ value }}</div>
  <Checkbox :value @change="value = !value" fake-attr="some" />
</template>

Checkbox.vue

<script setup lang="ts">
defineProps<{
  value: boolean
}>();
const $emit = defineEmits<{
  check: [boolean]
}>();
</script>

<template>
  <div>
    <input type="checkbox" @change="e => $emit('check')">
  </div>
</template>

As you see I can mistakenly put any attributes for Checkbox. Moreover I made a typo and put , as an attribute getting not so clear an error message at runtime which I had to debug with a conditional breakpoint:

Failed to execute 'setAttribute' on 'Element': ',' is not a valid attribute name.

A big problem is also to refactor, for example if I want to rename a property for more semantics I don't get any errors after the renaming since the old property would be become a valid extra attribute.

Any way to restrict component attributes to allowed ones (properties)?

3
  • can defineOptions({ inheritAttrs: false}) serve you in some way? Commented Oct 30, 2024 at 13:23
  • @BoussadjraBrahim added it in the playground and VSCode - no effect Commented Oct 30, 2024 at 13:26
  • 1
    inheritAttrs serves the purpose indeed. The effect is that it prevents unwanted attrs from being added to an element. It can prevent this error from happening too, but it looks like a corner case any way. Disallowing unknown attrs would cause more problems than solve them, especially with third-party comps that cannot be easily updated, starting with "class" and "style". If this is a recurring problem, you can add the validation of $attrs at runtime, and as for IDE, it could be this github.com/vuejs/language-tools/issues/… Commented Oct 30, 2024 at 17:13

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.