关于vue中模板引用的问题
我正在查看有关“refs”的 vue 文档,在它解释 v-for 内的 ref 的部分中给出了以下示例:
<script setup>
import { ref, onMounted } from 'vue'
const list = ref([
/* ... */
])
const itemRefs = ref([])
onMounted(() => console.log(itemRefs.value))
</script>
<template>
<ul>
<li v-for="item in list" ref="itemRefs">
{{ item }}
</li>
</ul>
</template>
我能理解它的用途
const itemRefs = ref([])
但我不明白为什么 ref 也应用于
const list = ref([ /* ... */ ])
在沙箱中,可以在不损害函数的情况下从“列表常量”中删除引用,那么这个常量内的真正应用程序是什么?
<script setup>
import { ref, onMounted } from 'vue'
// const with ref
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>
<script setup>
import { ref, onMounted } from 'vue'
// const without ref
const list = ([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> Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
使用 ref 将
list转换为反应变量。每当添加新项目或以其他方式改变它时,监视它的其他函数或模板部分都会更新。在没有 ref 的示例中,当您将新项目追加到列表中时,它不会自动在模板中呈现。我能理解你的困惑,我猜你可能来自 vue2 世界。我强烈建议您阅读有关反应性的 vue3 文档。