Vue3 使用 setup 语法在 v-for 循环中保存 ref 数组

方法一:使用函数

<template>
  <div>
    <span v-for="item in content" :ref="setRefs"> {{ item }}</span>
  </div>
</template>

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

const content = ref('hello world')
const refList = ref([])

const setRefs = (el) => {
  refList.value.push(el)
}

// 更新前需置空
onBeforeUpdate(() => {
  refList.value = []
})
</script>

效果一:

方法二:使用 toRef

这里是 ChatGPT 给出的答案

<template>
  <div>
    <span v-for="(item, index) in content" :key="index" :ref="setRefs(index)"> {{ item }}</span>
  </div>
</template>

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

const content = ref('hello world')
const refs = []

const setRefs = (index) => {
  const refValue = toRef(refs, index.toString())
  return (el) => {
    refValue.value = el
  }
}

onBeforeUpdate(() => {
  refs.length = 0
})
</script>

效果二:

posted @ 2022-05-16 09:49  to人间值得  阅读(2016)  评论(0)    收藏  举报