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)
});
文章讲述了在Vue3中,由于必须为每个动态渲染的DOM元素定义ref,当使用v-for时无法预先确定ref名称。解决方案是通过v-for的index给ref赋值,创建一个动态的ref数组并存储所有ref实例,以便后续遍历和使用。
6396

被折叠的 条评论
为什么被折叠?



