vue
可通过 ref
来获取当前 dom
,但是 vue3
必须定义 ref
的变量名,才能使用。
如果需要用 v-for 渲染的情况下,就无法做到提前定义 ref 变量名。
解决方案: 使用 v-for
循环出来的 dom
,ref
通过 index
下标来命名。
HTML 代码
<div v-for="item, index in listData" :key="item.id">
<li :ref="el => setSwipeCellRef(el, index)"></li>
</div>
JS代码
swipeCellRefList
里面放的是所有的 ref
// ref数组
const swipeCellRefList = ref<HTMLElement[]>([]);
// 动态设置ref
function setSwipeCellRef(el, index){
if (el) {
swipeCellRefList.value[index] = el;
}
}
使用的时候循环 swipeCellRefList
去使用就可以了
swipeCellRefList.value?.forEach((item: any) => {
console.log(item)
});