vue v3.2.25 或更高版本的 v-for 循环内的引用
Refs inside v-for Loop for vue v3.2.25 or above
我正在阅读documentation of vue 3 and I decided to test refs
in my local development environment. I am using vue version 3.2.31
and set up my project according to vue official guide. So for testing "refs" in my component, I just copied and pasted the code in this url,即vue 站点的Playground。这意味着我的组件的代码是这样的:
<script setup>
import { ref, onMounted } from 'vue'
const list = ref([1, 2, 3])
const itemRefs = ref([])
onMounted(() => {
console.log(itemRefs.value.map(i => i.textContent))
})
</script>
<template>
<ul>
<li v-for="item in list" ref="itemRefs">
{{ item }}
</li>
</ul>
</template>
但是在控制台中我收到一个空数组。我是否错过了查看 li
标签中的文本输出数组的操作?
这是一个已知错误 (vuejs/core#5525
),其中数组引用未正确填充。
一种解决方法是绑定一个将模板引用推送到数组中的函数:
<template>
<ul>
<li v-for="item in list" :ref="el => itemRefs.push(el)">
{{ item }}
</li>
</ul>
</template>
或通过包装器对象绑定 ref 数组(如 suggested in the original issue):
<script setup>
import { ref, onMounted } from 'vue'
const list = ref([1, 2, 3])
const itemRefs = ref([])
const skipUnwrap = { itemRefs }
onMounted(() => {
console.log(itemRefs.value.map(i => i.textContent))
})
</script>
<template>
<ul>
<li v-for="item in list" :ref="skipUnwrap.itemRefs">
{{ item }}
</li>
</ul>
</template>
我正在阅读documentation of vue 3 and I decided to test refs
in my local development environment. I am using vue version 3.2.31
and set up my project according to vue official guide. So for testing "refs" in my component, I just copied and pasted the code in this url,即vue 站点的Playground。这意味着我的组件的代码是这样的:
<script setup>
import { ref, onMounted } from 'vue'
const list = ref([1, 2, 3])
const itemRefs = ref([])
onMounted(() => {
console.log(itemRefs.value.map(i => i.textContent))
})
</script>
<template>
<ul>
<li v-for="item in list" ref="itemRefs">
{{ item }}
</li>
</ul>
</template>
但是在控制台中我收到一个空数组。我是否错过了查看 li
标签中的文本输出数组的操作?
这是一个已知错误 (vuejs/core#5525
),其中数组引用未正确填充。
一种解决方法是绑定一个将模板引用推送到数组中的函数:
<template>
<ul>
<li v-for="item in list" :ref="el => itemRefs.push(el)">
{{ item }}
</li>
</ul>
</template>
或通过包装器对象绑定 ref 数组(如 suggested in the original issue):
<script setup>
import { ref, onMounted } from 'vue'
const list = ref([1, 2, 3])
const itemRefs = ref([])
const skipUnwrap = { itemRefs }
onMounted(() => {
console.log(itemRefs.value.map(i => i.textContent))
})
</script>
<template>
<ul>
<li v-for="item in list" :ref="skipUnwrap.itemRefs">
{{ item }}
</li>
</ul>
</template>