利用 Vue inheritAttrs: false 繼承屬性到第二層子元件

https://stackoverflow.com/questions/56224091/what-are-inheritattrs-false-and-attrs-used-for-in-vue

用在:html 有複數層的子元件,加上 inheritAttrs: false  的話才能將 native attribute 透過 $attr 傳入第二層的 html tag 中、且不會影響第一層的 label

Vue2

例如下方範例的 required, placeholder

<template>
  <label>
      {{ label }}
      <input
        v-bind="$attrs"
        :value="value"
        @input="$emit('input', $event.target.value)"
      />
  </label>
</template>

<script>
export default Vue.extend({
  inheritAttrs: false,
}
</script>


// Usage
<LabelInput
  v-model="username"
  required
  placeholder="Enter your username"
  name="xxxxx"
/>

Vue3

使用 script setup  時寫法又大改啦XD

<script setup lang="ts">
  defineOptions({
    name: 'CustomName',
    inheritAttrs: false,
    customOptions: {},
  })
</script>

Comments

タイトルとURLをコピーしました