0 day streak
javascript / intermediate
Snippet

Handling Dynamic Template Refs in v-for Loops

In Vue 3, the ref attribute in a v-for loop can accept a function. This allows you to manually map elements to an object or array, solving the issue of managing a dynamic number of DOM references.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
<template>
<div v-for="id in list" :key="id" :ref="el => { if (el) elements[id] = el }"></div>
</template>
<script setup>
import { ref, onBeforeUpdate } from 'vue';
const elements = ref({});
onBeforeUpdate(() => { elements.value = {} });
</script>
vue
Breakdown
1
:ref="el => { if (el) elements[id] = el }"
Uses a function ref to capture the element and store it by ID.
2
onBeforeUpdate(() => { elements.value = {} })
Clears the collection before re-rendering to prevent stale references.