vue 中遍历数组
在 Vue.js 中,可以使用 v-for 指令遍历数组。该指令允许您为数组中的每个元素渲染一个特定的模板。
语法:
<code class="html"><template v-for="item in items"> <!-- 模板内容 --> </template></code>
参数:
-
item:数组中的当前元素 -
items:要遍历的数组
示例:
立即学习“前端免费学习笔记(深入)”;
<code class="html"><template>
<ul>
<li v-for="item in items">{{ item }}</li>
</ul>
</template>
<script>
import { ref } from 'vue';
export default {
setup() {
const items = ref(['Apple', 'Banana', 'Orange']);
return {
items,
};
},
};
</script></code>在这个示例中,v-for 指令用于遍历 items 数组,并为每个数组元素渲染一个 <li> 元素。
其他功能:
- v-for.of:指定要遍历的数组或可迭代对象。
- v-for.in:指定要遍历的对象的属性或键。
- v-for.index:获取当前遍历到的数组索引。
- v-for.key:指定每个元素的唯一键,用于优化列表渲染。
更多示例:
- 遍历对象数组:
<code class="html"><template v-for="item in items">
<h1>{{ item.name }}</h1>
<p>{{ item.age }}</p>
</template></code>- 使用 v-for.index:
<code class="html"><template v-for="(item, index) in items">
<p>{{ index + 1 }}. {{ item }}</p>
</template></code>










