vue3中ref动态绑定【技巧】

平常时候绑定ref

xml 复制代码
<script>
const tempRef = ref<HTMLElement>()
</script>
<template>
<div ref='tempRef'></div>
</template>

在一些场景需要动态绑定ref, ref设置是未知的需要根据动态数据来决定,那么我们需要定义一个对象进行存储绑定的ref,例:

typescript 复制代码
<script>
interface DataItem {
    id:string,
    name:string
}
const dataList:DataItem[] = [
{
    id="1",
    name:'标题1'
},
{
    id="2",
    name:'标题2'
},
{
    id="3",
    name:'标题3'
}
]
const tempRefs = ref({} as any);
const handleSetTempMap = (el: Element, item: DataItem)=>{
    if (el) {
    tempRefs.value[`temp_{item.id}`] = el;
  }
}


</script>
<template>
<div v-for="item in dataList" :key="item.id" 
:ref="(el:Element) => handleSetTempMap(el, item)"
>
</div>
</template>
相关推荐
滴滴答答哒4 小时前
VUE3+element-plus MultiSelect 多选下拉组件
前端·javascript·vue.js
其美杰布-富贵-李4 小时前
04 watch 与 Vue 响应式数据流
前端·javascript·vue.js
其美杰布-富贵-李7 小时前
03 ref、reactive 与 computed 响应式数据
前端·javascript·vue.js
嘟嘟07178 小时前
useRef + Web Worker:React 中的耗时计算不卡页面
javascript·vue.js
万敏8 小时前
Vue3 全栈实战第五周:Vitest 单元测试从零搭建实战记录
vue.js·node.js·全栈
sugar__salt11 小时前
跟着 Demo 学 Pinia:两种仓库写法 + 完整 TodoList 复现
前端·javascript·vue.js·前端框架·vue
A242073493014 小时前
Vue + TypeScript 请求数据后结合 Element UI 实现树形菜单与下拉选择
vue.js·ui·typescript
java1234_小锋15 小时前
Vue3专题 - 条件渲染
前端·javascript·vue.js
鸽鸽15 小时前
Vue 3 API 完全指南:从 Options 到 Composition 的进阶之路
前端·vue.js
肉肉不吃 肉15 小时前
无渲染组件和组合式函数
前端·javascript·vue.js