Vue 循环语句
在 Vue 中,我们使用 v-for 指令来进行循环渲染。它可以基于一个数组来渲染一个列表,也可以用于遍历一个对象或一个数字范围。
v-for 遍历数组
v-for 指令需要使用一种特殊的语法,形式为 item in items,其中 items 是源数据数组,而 item 则是被迭代的数组元素的别名。
vue
<script setup>
import { ref } from 'vue'
const items = ref([
{ id: 1, message: 'Foo' },
{ id: 2, message: 'Bar' }
])
</script>
<template>
<ul>
<li v-for="item in items" :key="item.id">
{{ item.message }}
</li>
</ul>
</template>v-for 还支持一个可选的第二个参数,即当前项的索引。
vue
<template>
<ul>
<li v-for="(item, index) in items" :key="item.id">
{{ index }} - {{ item.message }}
</li>
</ul>
</template>:key 的重要性
v-for 指令要求我们提供一个 key attribute。key 是一个特殊的 attribute,Vue 用它来追踪每个节点的身份,从而可以重用和重新排序现有元素。key 的值必须是唯一的字符串或数字。
强烈建议在 v-for 中始终提供 key,除非你迭代的 DOM 内容非常简单,或者你刻意依赖默认行为以获取性能上的提升。
v-for 遍历对象
你也可以使用 v-for 来遍历一个对象的 property。
vue
<script setup>
import { reactive } from 'vue'
const myObject = reactive({
title: 'How to do lists in Vue',
author: 'Jane Doe',
publishedAt: '2016-04-10'
})
</script>
<template>
<ul>
<li v-for="(value, key, index) in myObject" :key="key">
{{ index }}. {{ key }}: {{ value }}
</li>
</ul>
</template>遍历对象时,会按 Object.keys() 的结果遍历,但不能保证在所有 JavaScript 引擎下的结果都一致。v-for 支持可选的第二个(键)和第三个(索引)参数。
v-for 遍历数字范围
v-for 也可以接受一个整数。在这种情况下,它会把模板重复对应次数。
vue
<template>
<span v-for="n in 10" :key="n">{{ n }} </span>
</template>输出将会是:1 2 3 4 5 6 7 8 9 10
在 <template> 上使用 v-for
类似于 v-if,你也可以利用带有 v-for 的 <template> 标签来渲染一个包含多个元素的块。例如:
vue
<ul>
<template v-for="item in items" :key="item.id">
<li>{{ item.message }}</li>
<li class="divider" role="presentation"></li>
</template>
</ul>v-for 与 v-if
当它们同时存在于一个节点上时,v-if 比 v-for 的优先级更高。这意味着 v-if 的条件将无法访问到 v-for 作用域内定义的变量。
这可以通过将 v-if 移动到一个包裹 v-for 的 <template> 标签上来解决:
vue
<template v-if="shouldRenderItems">
<ul>
<li v-for="item in items" :key="item.id">
{{ item.message }}
</li>
</ul>
</template>如果你只想渲染部分项,可以在计算属性中先对列表进行过滤,然后在 v-for 中直接使用过滤后的列表。