vue3動態(tài)綁定ref并獲取其dom實現(xiàn)方式
更新時間:2025年07月23日 14:41:30 作者:meng半顆糖
Vue3中動態(tài)綁定ref建議用對象存儲,通過索引訪問嵌套元素;或使用計算屬性獲取DOM,兩種方法可提升靈活性,適用于v-for循環(huán)場景,便于操作單/多層嵌套結構
vue3動態(tài)綁定ref并獲取其dom
方法1:v-for
在 v-for 中建議用對象存儲 refs 而非數(shù)組
- 函數(shù)參數(shù)
el:動態(tài)綁定時會傳入當前 DOM 元素或組件實例
<template>
<div v-for="item in items" :key="item.id">
<div :ref="(el) => setItemRef(el, item.id)"></div>
</div>
</template>
<script setup>
import { ref } from 'vue'
const items = ref([{ id: 1 }, { id: 2 }])
const itemRefs = ref({})
const setItemRef = (el, id) => {
if (el) {
itemRefs.value[id] = el // 存儲 DOM 引用
}
}
onMounted(() => {
console.log(itemRefs.value) // 輸出 {1: div, 2: div}
})
</script>
for循環(huán) 可使用單/多層 嵌套
<!-- 單層循環(huán) -->
<div v-for="(item, index) in list" :key="index">
<input :ref="(el) => (refsArray[index] = el)" />
</div>
<!-- 嵌套循環(huán) -->
<div v-for="(group, i) in groups" :key="i">
<div v-for="(item, j) in group.items" :key="j">
<input :ref="(el) => (nestedRefs[i][j] = el)" />
</div>
</div>
通過 refsArray[index] 或 nestedRefs[i][j] 即可訪問嵌套元素
方法2:使用計算屬性
const getRefName = (index) => `itemRef_${index}`
總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
vue.js的雙向數(shù)據綁定Object.defineProperty方法的神奇之處
今天小編就為大家分享一篇關于vue.js的雙向數(shù)據綁定Object.defineProperty方法的神奇之處,小編覺得內容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-01-01
vue中實現(xiàn)全屏以及對退出全屏的監(jiān)聽
本文主要介紹了vue中實現(xiàn)全屏以及對退出全屏的監(jiān)聽,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-07-07

