Vue3 提供了多种循环语句,可以用来遍历数组、对象、字符串等数据。下面是 Vue3 中常用的循环语句:
1. v-for
v-for
指令用于遍历数组或对象。语法如下:
<template>
<ul>
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
</ul>
</template>
在上面的代码中,v-for
指令将遍历 items
数组,每个元素将被渲染到 <li>
元素中,并将 item
对象的 name
属性显示在 <li>
元素中。
2. v-for with index
v-for
指令可以使用 index
属性来访问当前循环的索引。语法如下:
<template>
<ul>
<li v-for="(item, index) in items" :key="item.id">{{ index }}: {{ item.name }}</li>
</ul>
</template>
在上面的代码中,v-for
指令将遍历 items
数组,每个元素将被渲染到 <li>
元素中,并将当前循环的索引 index
和 item
对象的 name
属性显示在 <li>
元素中。
3. v-for with object
v-for
指令可以使用对象循环遍历对象的属性。语法如下:
<template>
<ul>
<li v-for="(key, value) in obj" :key="key">{{ key }}: {{ value }}</li>
</ul>
</template>
在上面的代码中,v-for
指令将遍历 obj
对象,每个属性将被渲染到 <li>
元素中,并将属性名 key
和 属性值 value
显示在 <li>
元素中。
4. v-for with array of objects
v-for
指令可以使用数组循环遍历数组中的对象。语法如下:
<template>
<ul>
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
</ul>
</template>
在上面的代码中,v-for
指令将遍历 items
数组,每个对象将被渲染到 <li>
元素中,并将对象的 name
属性显示在 <li>
元素中。
5. v-for with recursive component
v-for
指令可以使用递归组件来遍历数组或对象。语法如下:
<template>
<ul>
<li v-for="item in items" :key="item.id">
<MyComponent v-if="item.children.length > 0" :key="item.id" :children="item.children" />
</li>
</ul>
</template>
在上面的代码中,v-for
指令将遍历 items
数组,每个对象将被渲染到 <li>
元素中,并将对象的 children
属性作为递归组件的 props。