0 day streak
javascript / expert
Snippet

Template Ref Map for Dynamic Child Management

When dealing with dynamic lists, assigning a static ref string is insufficient. By using a function ref that populates a Map, you can precisely target specific DOM elements by their unique IDs without relying on array indices which might shift during re-renders.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
const itemRefs = new Map();
const setItemRef = (el, id) => {
if (el) {
itemRefs.set(id, el);
} else {
itemRefs.delete(id);
}
};
// Usage in template:
// <div v-for="item in items" :key="item.id" :ref="el => setItemRef(el, item.id)">
vue
Breakdown
1
const itemRefs = new Map();
Initialize a Map to store DOM elements associated with unique identifiers.
2
const setItemRef = (el, id) => { ... }
A callback function that Vue executes whenever the element is mounted or unmounted.
3
itemRefs.set(id, el);
Store the element in the map if it exists (mounted).
4
itemRefs.delete(id);
Remove the entry if the element is null (unmounted).