新聞中心
該頁(yè)面假設(shè)你已經(jīng)閱讀過(guò)了組件基礎(chǔ)。如果你還對(duì)組件不太了解,推薦你先閱讀它。
創(chuàng)新互聯(lián)是一家專(zhuān)業(yè)從事成都網(wǎng)站設(shè)計(jì)、成都做網(wǎng)站的網(wǎng)絡(luò)公司。作為專(zhuān)業(yè)網(wǎng)站設(shè)計(jì)公司,創(chuàng)新互聯(lián)依托的技術(shù)實(shí)力、以及多年的網(wǎng)站運(yùn)營(yíng)經(jīng)驗(yàn),為您提供專(zhuān)業(yè)的成都網(wǎng)站建設(shè)、成都全網(wǎng)營(yíng)銷(xiāo)推廣及網(wǎng)站設(shè)計(jì)開(kāi)發(fā)服務(wù)!
一個(gè)非 prop 的 attribute 是指?jìng)飨蛞粋€(gè)組件,但是該組件并沒(méi)有相應(yīng) props 或 emits 定義的 attribute。常見(jiàn)的示例包括 class、style 和 id 屬性。
#Attribute 繼承
當(dāng)組件返回單個(gè)根節(jié)點(diǎn)時(shí),非 prop attribute 將自動(dòng)添加到根節(jié)點(diǎn)的 attribute 中。例如,在 組件的實(shí)例中:
app.component('date-picker', {
template: `
`
})
如果我們需要通過(guò) data status property 定義 組件的狀態(tài),它將應(yīng)用于根節(jié)點(diǎn) (即 div.date-picker)。
同樣的規(guī)則適用于事件監(jiān)聽(tīng)器:
app.component('date-picker', {
created() {
console.log(this.$attrs) // { onChange: () => {} }
}
})
當(dāng)有一個(gè) HTML 元素將 change 事件作為 date-picker 的根元素時(shí),這可能會(huì)有幫助。
app.component('date-picker', {
template: `
`
})
在這種情況下,change 事件監(jiān)聽(tīng)器從父組件傳遞到子組件,它將在原生 select 的 change 事件上觸發(fā)。我們不需要顯式地從 date-picker 發(fā)出事件:
const app = Vue.createApp({
methods: {
showChange(event) {
console.log(event.target.value) // 將記錄所選選項(xiàng)的值
}
}
})
#禁用 Attribute 繼承
如果你不希望組件的根元素繼承 attribute,你可以在組件的選項(xiàng)中設(shè)置 inheritAttrs: false。例如:
禁用 attribute 繼承的常見(jiàn)情況是需要將 attribute 應(yīng)用于根節(jié)點(diǎn)之外的其他元素。
通過(guò)將 inheritAttrs 選項(xiàng)設(shè)置為 false,你可以訪問(wèn)組件的 $attrs property,該 property 包括組件 props 和 emits property 中未包含的所有屬性 (例如,class、style、v-on 監(jiān)聽(tīng)器等)。
使用上一節(jié)中的 date-picker 組件示例,如果需要將所有非 prop attribute 應(yīng)用于 input 元素而不是根 div 元素,則可以使用 v-bind 縮寫(xiě)來(lái)完成。
app.component('date-picker', {
inheritAttrs: false,
template: `
`
})
有了這個(gè)新配置,data status attribute 將應(yīng)用于 input 元素!
#多個(gè)根節(jié)點(diǎn)上的 Attribute 繼承
與單個(gè)根節(jié)點(diǎn)組件不同,具有多個(gè)根節(jié)點(diǎn)的組件不具有自動(dòng) attribute 回退行為。如果未顯式綁定 $attrs,將發(fā)出運(yùn)行時(shí)警告。
// 這將發(fā)出警告
app.component('custom-layout', {
template: `
...
...
`
})
// 沒(méi)有警告,$attrs被傳遞到元素
app.component('custom-layout', {
template: `
...
...
`
}) 網(wǎng)頁(yè)標(biāo)題:創(chuàng)新互聯(lián)VUE3教程:Vue3.0非Prop的Attribute
轉(zhuǎn)載來(lái)源:http://www.5511xx.com/article/cdhicph.html


咨詢(xún)
建站咨詢(xún)

