W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
在 Vue 2 中,在 v-for
里使用的 ref
attribute 會(huì)用 ref 數(shù)組填充相應(yīng)的 $refs
property。當(dāng)存在嵌套的 v-for
時(shí),這種行為會(huì)變得不明確且效率低下。
在 Vue 3 中,這樣的用法將不再在 $ref
中自動(dòng)創(chuàng)建數(shù)組。要從單個(gè)綁定獲取多個(gè) ref,請(qǐng)將 ref
綁定到一個(gè)更靈活的函數(shù)上 (這是一個(gè)新特性):
<div v-for="item in list" :ref="setItemRef"></div>
結(jié)合選項(xiàng)式 API:
export default {
data() {
return {
itemRefs: []
}
},
methods: {
setItemRef(el) {
this.itemRefs.push(el)
}
},
beforeUpdate() {
this.itemRefs = []
},
updated() {
console.log(this.itemRefs)
}
}
結(jié)合組合式 API:
import { ref, onBeforeUpdate, onUpdated } from 'vue'
export default {
setup() {
let itemRefs = []
const setItemRef = el => {
itemRefs.push(el)
}
onBeforeUpdate(() => {
itemRefs = []
})
onUpdated(() => {
console.log(itemRefs)
})
return {
itemRefs,
setItemRef
}
}
}
注意:
itemRefs
不必是數(shù)組:它也可以是一個(gè)對(duì)象,其 ref 會(huì)通過迭代的 key 被設(shè)置。itemRef
也可以是響應(yīng)式的且可以被監(jiān)聽。Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: