vue3 循环设置 ref 并获取

vue可通过 ref 来获取当前 dom,但是 vue3 必须定义 ref 的变量名,才能使用。
如果需要用 v-for 渲染的情况下,就无法做到提前定义 ref 变量名。

解决方案: 使用 v-for 循环出来的 domref 通过 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)
});

相关推荐

  1. vue3 循环设置 ref 获取

    2024-03-16 18:10:02       38 阅读
  2. Vue3 动态设置 ref

    2024-03-16 18:10:02       63 阅读
  3. vue3 #ref #reactive

    2024-03-16 18:10:02       48 阅读
  4. ref&reactive vue3

    2024-03-16 18:10:02       36 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-16 18:10:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-16 18:10:02       101 阅读
  3. 在Django里面运行非项目文件

    2024-03-16 18:10:02       82 阅读
  4. Python语言-面向对象

    2024-03-16 18:10:02       91 阅读

热门阅读

  1. docker安装rabbitmq

    2024-03-16 18:10:02       36 阅读
  2. Linux守护进程

    2024-03-16 18:10:02       38 阅读
  3. 每日一题 第五期 洛谷 图的遍历

    2024-03-16 18:10:02       42 阅读
  4. 最长连续序列 - LeetCode 热题 3

    2024-03-16 18:10:02       38 阅读