當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Vue.js inheritAttrs用法及代碼示例

類型

interface ComponentOptions {
  inheritAttrs?: boolean // default: true
}

細節

默認情況下,不被識別為 props 的父範圍屬性綁定將 "fallthrough"。這意味著當我們有一個single-root 組件時,這些綁定將作為普通 HTML 屬性應用於子組件的根元素。在創作包裝目標元素或另一個組件的組件時,這可能並不總是期望的行為。通過將 inheritAttrs 設置為 false ,可以禁用此默認行為。這些屬性可通過 $attrs 實例屬性獲得,並且可以使用 v-bind 顯式綁定到非根元素。

示例

<script>
export default {
  inheritAttrs: false,
  props: ['label', 'value'],
  emits: ['input']
}
</script>

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

在使用 <script setup> 的組件中聲明此選項時,需要單獨的 <script> 塊:

<script>
export default {
  inheritAttrs: false
}
</script>

<script setup>
defineProps(['label', 'value'])
defineEmits(['input'])
</script>

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

相關用法


注:本文由純淨天空篩選整理自vuejs.org大神的英文原創作品 inheritAttrs。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。