您好,登錄后才能下訂單哦!
這篇文章主要介紹“Vue2和Vue3在v-for遍歷時(shí)ref獲取dom節(jié)點(diǎn)的區(qū)別是什么”的相關(guān)知識,小編通過實(shí)際案例向大家展示操作過程,操作方法簡單快捷,實(shí)用性強(qiáng),希望這篇“Vue2和Vue3在v-for遍歷時(shí)ref獲取dom節(jié)點(diǎn)的區(qū)別是什么”文章能幫助大家解決問題。
在 vue 2 中,如果給 v-for 綁定一個(gè) ref ,通過這個(gè) ref 可以獲取到全部 v-for 的節(jié)點(diǎn)。
HTML
<div id='app'> <div> <p v-for="item in renderData" :key="item.name" ref="nodes">{{item.name}}</p> </div> </div>
JS
data() { return { renderData: [ { name: 'a' }, { name: 'b' }, { name: 'c' }, { name: 'd' }, { name: 'f' } ] } }, mounted() { console.log(this.$refs.nodes) }
從而可以獲得所有 v-for 的節(jié)點(diǎn)數(shù)組:
所以你可以在自定義觸發(fā)事件中將索引傳入,就可以在 this.$refs.nodes[index]
中獲取觸發(fā)事件的那個(gè) dom 。
在 vue 3 中,對 v-for 的一體化(數(shù)組化)處理已經(jīng)取消,變?yōu)楹瘮?shù)處理 ref 。
如果你像 vue 2 中綁定:
<div> <p v-for="item in renderData" :key="item.name" ref="nodes">{{item.name}}</p> </div>
此時(shí)通過 this.$refs.nodes
只能獲取遍歷的最后一個(gè)節(jié)點(diǎn) dom 。
如果要實(shí)現(xiàn) vue 2 相同的數(shù)組,你可以對 ref 進(jìn)行自定義處理:
HTML
<div> <p v-for="item in renderData" :key="item.name" ref="handleNodes">{{item.name}}</p> </div>
JS
data() { return { nodes: [] } }, methods: { handleNodes(el) { this.nodes.push(el) } }
也就是說 ref 的處理方式變?yōu)榱撕瘮?shù),這個(gè)函數(shù)默認(rèn)傳入該節(jié)點(diǎn)。
當(dāng)然,如果你不在 v-for 上使用,只是單純的加入單個(gè) ref ,使用方法和 vue 2 沒有任何區(qū)別。
關(guān)于“Vue2和Vue3在v-for遍歷時(shí)ref獲取dom節(jié)點(diǎn)的區(qū)別是什么”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識,可以關(guān)注億速云行業(yè)資訊頻道,小編每天都會為大家更新不同的知識點(diǎn)。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。