--- title: Template Ref Array Order Not Guaranteed in v-for impact: MEDIUM impactDescription: Refs collected from v-for may not match source array order, causing index-based bugs type: gotcha tags: [vue3, template-refs, v-for, arrays, ordering] --- # Template Ref Array Order Not Guaranteed in v-for **Impact: MEDIUM** - When using template refs inside `v-for`, Vue collects the element references into an array. However, this array does NOT guarantee the same order as the source array. Relying on index-based access can lead to subtle bugs. This caveat is not obvious and can cause hard-to-debug issues when you assume the ref array matches your data order. > **Warning: `useTemplateRef()` does NOT work with v-for refs in Vue 3.5** > > The `useTemplateRef()` API returns `null` when used with refs inside `v-for`. This is a known limitation. You must use the legacy pattern with `ref()` and a matching template ref name: > > ```ts > // Does NOT work with v-for - returns null > const itemRefs = useTemplateRef('items') > > // Works with v-for - use this pattern instead > const items = ref([]) // name must match ref="items" in template > ``` > > The examples in this rule show `useTemplateRef()` for illustration, but in practice you should use the legacy `ref()` pattern for v-for scenarios until this limitation is addressed. ## Task Checklist - [ ] Never assume ref array indices match source data array indices - [ ] Use data attributes or other identifiers to correlate refs with data - [ ] Consider function refs for complex scenarios requiring ordered access - [ ] Test with dynamic list operations (add, remove, reorder) to verify behavior **Incorrect:** ```vue ``` **Correct:** ```vue ``` ```vue ``` ```vue ``` ## Reference - [Vue.js Template Refs - Refs inside v-for](https://vuejs.org/guide/essentials/template-refs.html#refs-inside-v-for)