#When I use a v-for loop to make a array of refs it comes back as undefined

3 messages · Page 1 of 1 (latest)

pastel pendantBOT
#

Hi @mossy roost. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

When using refs with v-for in Vue 3/Nuxt 3, the array of refs is only populated after the component has mounted. However, there are a few important caveats:

  1. Accessing the Ref Array: If you use a template ref (like useTemplateRef or ref) with v-for, you get an array of refs. But, when you use a ref on a custom component, you get the component instance, not the DOM element, unless the child component exposes the element using defineExpose.

  2. Access Timing: You must access the refs after the DOM is rendered (e.g., in onMounted or after nextTick). However, in your code, T[0].value may be undefined if the refs are not yet populated or if the ref is not set up correctly.

  3. Correct Ref Usage in Template: In your template, you should use :ref="element" (with element being a string or a function), but in <script setup>, useTemplateRef('element') is not standard Vue usage. Typically, you would do:

<script setup>
import { ref, onMounted, nextTick } from 'vue'

const elements = ref([])

onMounted(async () => {
  await nextTick()
  if (elements.value[0]) {
    elements.value[0].innerHTML = "test"
  }
})
</script>

<template>
  <div
    v-for="i in 10"
    :key="i"
    class="myClass"
    :id="i"
    ref="elements"
  ></div>
</template>
  • Here, elements is a ref to an array of DOM elements, and after mounting (and nextTick), you can safely access elements.value[0].
  1. Custom Components: If you use ref on a custom component, you need to use defineExpose in the child to expose the internal ref to the parent. Otherwise, you'll get the component instance, not the DOM element. See this explanation for details.
#

Summary:

  • Use ref([]) for the array of refs.
  • Use ref="elements" in the template.
  • Access elements.value after onMounted and nextTick.
  • For custom components, use defineExpose to expose internal refs.

If you follow this pattern, you should be able to access your array of refs as expected. If you still get undefined, double-check that your ref is correctly set up and that you are accessing it after the DOM is rendered.

References:


Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: