简体   繁体   中英

Vue - How to use a dynamic ref with composition API

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM