Home > Blockchain >  Vue - How to use a dynamic ref with composition API
Vue - How to use a dynamic ref with composition API

Time:01-16

I am using the composition API in Vue 3 and want to define a ref to a component. Usually that would be done by adding ref="name" to the template and then defining a ref with the same name: const name = ref(null). The problem is I want to use dynamic ref names. Any idea how to solve this?

In the options API I could do something like this: :ref="name${x}" and then access it in the code like this: this.$refs[name${x}]. But with the composition API I don't have access to $refs. Is there a way to do this without using a function inside the template ref?

CodePudding user response:

The :ref prop accepts a function (see documentation), which you can use to assign it to the variable you want:

<script setup>
const dynamicRef = ref(null);
</script>

<template>
  <Count :ref="(el) => dynamicRef = el" />
</template>

Vue playground example

CodePudding user response:

I guess the Refs inside v-for is a better match for what you are trying to achieve.

Requires Vue v3.2.25 or above

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

const list = ref([1, 2, 3])

const itemRefs = ref([])

onMounted(() => {
  alert(itemRefs.value.map(i => i.textContent))
})
</script>

<template>
  <ul>
    <li v-for="item in list" ref="itemRefs">
      {{ item }}
    </li>
  </ul>
</template>

Vue SFC Playground

  • Related