v-for
用来遍历数组或对象,并动态生成一组DOM元素。
- 渲染简单的数组
<template> <ul> <li v-for="fruit in fruits" :key="fruit">{ {fruit}}</li> </ul> </template> <script setup> import {ref} from 'vue'; const fruits = ref({'苹果', '香蕉', '橙子'}); //水果列表 </script>
:key="fruit" :为每个渲染的列表项指定唯一的key,这是vue用来高效更新DOM的关键。
-
渲染数组对象
渲染用户列表
<template>
<ul>
<li v-for="user in users" :key="user.id">
{
{user.name}} - {
{user.age}}岁
</li>
</ul>
</template>
<script setup>
import { ref } from 'vue';
const users = ref({
{id:1,name: 'zs', age: 25},
{id:2,name: 'ls', age: 22},
{id:3,name: 'ww', age: 23},
})
</script>
:key="user.id"
: 使用user.id
作为唯一的key
,以帮助 Vue 跟踪每个列表项。
3. 渲染带有索引的数组
有时你可能需要获取当前元素的索引值
<template>
<ul>
<!-- 遍历 fruits 数组,同时获取每个元素的索引 -->
<li v-for="(fruit, index) in fruits" :key="index">
{
{ index + 1 }}. {
{ fruit }}
</li>
</ul>
</template>
<script setup>
import { ref } from 'vue';
const fruits = ref(['苹果', '香蕉', '橙子']); // 水果列表
</script>
4.渲染对象的属性
<template>
<ul>
<li v-for="([key,value],index) in objection" :key="index">
{
{key}} : {
{value}}
</li>
</ul>
</template>
<script setup>
import { ref, computed} from 'vue';
const obj = ref({
name: 'Alice',
age: 30,
profession: 'Engineer'
});
//将对象转换为键值对数组
const objection = computed(() => Object.entries(obj.value));
</script>
Object.entries(obj.value)
: 将对象转换为一个包含键值对的数组。