Vue 3.0 非Prop的Attribute

2021-07-16 11:29 更新

該頁面假設你已經閱讀過了組件基礎。如果你還對組件不太了解,推薦你先閱讀它。

一個非 prop 的 attribute 是指傳向一個組件,但是該組件并沒有相應 propsemits 定義的 attribute。常見的示例包括 classstyleid 屬性。

#Attribute 繼承

當組件返回單個根節(jié)點時,非 prop attribute 將自動添加到根節(jié)點的 attribute 中。例如,在 <date-picker> 組件的實例中:

app.component('date-picker', {
  template: `
    <div class="date-picker">
      <input type="datetime" />
    </div>
  `
})

如果我們需要通過 data status property 定義 <date-picker> 組件的狀態(tài),它將應用于根節(jié)點 (即 div.date-picker)。

<!-- 具有非prop attribute的Date-picker組件-->
<date-picker data-status="activated"></date-picker>


<!-- 渲染 date-picker 組件 -->
<div class="date-picker" data-status="activated">
  <input type="datetime" />
</div>

同樣的規(guī)則適用于事件監(jiān)聽器:

<date-picker @change="submitChange"></date-picker>

app.component('date-picker', {
  created() {
    console.log(this.$attrs) // { onChange: () => {}  }
  }
})

當有一個 HTML 元素將 change 事件作為 date-picker 的根元素時,這可能會有幫助。

app.component('date-picker', {
  template: `
    <select>
      <option value="1">Yesterday</option>
      <option value="2">Today</option>
      <option value="3">Tomorrow</option>
    </select>
  `
})

在這種情況下,change 事件監(jiān)聽器從父組件傳遞到子組件,它將在原生 selectchange 事件上觸發(fā)。我們不需要顯式地從 date-picker 發(fā)出事件:

<div id="date-picker" class="demo">
  <date-picker @change="showChange"></date-picker>
</div>

const app = Vue.createApp({
  methods: {
    showChange(event) {
      console.log(event.target.value) // 將記錄所選選項的值
    }
  }
})

#禁用 Attribute 繼承

如果你希望組件的根元素繼承 attribute,你可以在組件的選項中設置 inheritAttrs: false。例如:

禁用 attribute 繼承的常見情況是需要將 attribute 應用于根節(jié)點之外的其他元素。

通過將 inheritAttrs 選項設置為 false,你可以訪問組件的 $attrs property,該 property 包括組件 propsemits property 中未包含的所有屬性 (例如,class、stylev-on 監(jiān)聽器等)。

使用上一節(jié)中的 date-picker 組件示例,如果需要將所有非 prop attribute 應用于 input 元素而不是根 div 元素,則可以使用 v-bind 縮寫來完成。

app.component('date-picker', {
  inheritAttrs: false,
  template: `
    <div class="date-picker">
      <input type="datetime" v-bind="$attrs" />
    </div>
  `
})

有了這個新配置,data status attribute 將應用于 input 元素!

<!-- Date-picker 組件 使用非 prop attribute -->
<date-picker data-status="activated"></date-picker>


<!-- 渲染 date-picker 組件 -->
<div class="date-picker">
  <input type="datetime" data-status="activated" />
</div>

#多個根節(jié)點上的 Attribute 繼承

與單個根節(jié)點組件不同,具有多個根節(jié)點的組件不具有自動 attribute 回退行為。如果未顯式綁定 $attrs,將發(fā)出運行時警告。

<custom-layout id="custom-layout" @click="changeValue"></custom-layout>

// 這將發(fā)出警告
app.component('custom-layout', {
  template: `
    <header>...</header>
    <main>...</main>
    <footer>...</footer>
  `
})


// 沒有警告,$attrs被傳遞到<main>元素
app.component('custom-layout', {
  template: `
    <header>...</header>
    <main v-bind="$attrs">...</main>
    <footer>...</footer>
  `
})
以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號