平常时候绑定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>