Vue3 `inheritAttrs`屬性繼承與`$attrs`使用與講解

  • $attrs和inheritAttrs用法

  • $attrs屬性解釋:包含了父作用域中不作為組件 props 或自定義事件的 attribute 綁定和事件。當(dāng)一個(gè)組件沒有聲明任何 props 時(shí),這里會(huì)包含所有父作用域的綁定,并且可以通過 v-bind="$attrs" 傳入內(nèi)部組件,這在創(chuàng)建高階的組件時(shí)會(huì)非常有用。

  • inheritAttrs屬性解釋:如果你不希望組件的根元素繼承特性,你可以在組件的選項(xiàng)中設(shè)置 inheritAttrs: false

舉個(gè)例子

打開在線 Vue SFC https://sfc.vuejs.org/

App.vue代碼如下

<script setup>
import { reactive } from 'vue'
import MyInput from './MyInput.vue'

const state = reactive({
  text: "",
  pass: "",
});
</script>

<template>
  <div>
    <MyInput type="text" placeholder="輸入用戶名" v-model="state.text" />
    <MyInput type="text" placeholder="輸入密碼" v-model="state.pass" />
  </div>
</template>

子組件 MyInput.vue 設(shè)置 inheritAttrs: true(默認(rèn))

<template>
  <div class="input">
    <input v-bind="$attrs" v-model="modelValue" />
  </div>
</template>
<script>
export default {
  // inheritAttrs: false,
  props: {
    modelValue: [String, Number],
  },
};
</script>

此時(shí)我們右鍵檢查輸入框查看渲染的Dom


inheritAttrs:true

取消注釋 inheritAttrs: false, 再次檢查Dom

inheritAttrs: false

小結(jié):
由上述例子可以看出,子組件的props中未注冊父組件傳遞過來的屬性

  • 當(dāng)設(shè)置inheritAttrs:true時(shí),子組件的頂層標(biāo)簽元素中會(huì)渲染出父組件傳遞過來的屬性(例如:type="text"等)
  • 當(dāng)設(shè)置inheritAttrs: false時(shí),子組件的頂層標(biāo)簽元素中不會(huì)渲染出父組件傳遞過來的屬性
  • 不管inheritAttrs為true或者false,子組件中都能通過$attrs屬性獲取到父組件中傳遞過來的屬性。
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容