Vue3 v-for Directive
v-forThe directive is used to render elements multiple times based on source data, and is the core directive for implementing list rendering in Vue.
Basic Description
v-forThe directive repeatedly renders elements based on an array or object. It allows you to repeatedly render a group of similar elements and use values from the data source.
- Expected Type: Array | Object | number | string | Iterable
- Function: List rendering, renders elements multiple times based on source data.
Basic Syntax
Example
<!-- Array iteration -->
<li v-for="item in items">{{ item }}</li>
<!-- Iteration with index -->
<li v-for="(item, index) in items">{{ index }} - {{ item }}</li>
<!-- Object iteration -->
<li v-for="(value, key) in object">{{ key }}: {{ value }}</li>
<!-- Numeric iteration -->
<li v-for="n in 5">{{ n }}</li>
<li v-for="item in items">{{ item }}</li>
<!-- Iteration with index -->
<li v-for="(item, index) in items">{{ index }} - {{ item }}</li>
<!-- Object iteration -->
<li v-for="(value, key) in object">{{ key }}: {{ value }}</li>
<!-- Numeric iteration -->
<li v-for="n in 5">{{ n }}</li>
Usage Scenarios
1. Array Iteration
Example
<template>
<ul>
<li v-for="(fruit, index) in fruits" :key="index">
{{ index + 1 }}. {{ fruit }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
fruits: ['apple', 'banana', 'orange', 'grape']
}
}
}
</script>
<ul>
<li v-for="(fruit, index) in fruits" :key="index">
{{ index + 1 }}. {{ fruit }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
fruits: ['apple', 'banana', 'orange', 'grape']
}
}
}
</script>
2. Object Array Iteration
Example
<template>
<table>
<tr v-for="person in people" :key="person.id">
<td>{{ person.id }}</td>
<td>{{ person.name }}</td>
<td>{{ person.age }}</td>
</tr>
</table>
</template>
<script>
export default {
data() {
return {
people: [
{ id: 1, name: 'Zhang San', age: 25 },
{ id: 2, name: 'Li Si', age: 30 }
]
}
}
}
</script>
<table>
<tr v-for="person in people" :key="person.id">
<td>{{ person.id }}</td>
<td>{{ person.name }}</td>
<td>{{ person.age }}</td>
</tr>
</table>
</template>
<script>
export default {
data() {
return {
people: [
{ id: 1, name: 'Zhang San', age: 25 },
{ id: 2, name: 'Li Si', age: 30 }
]
}
}
}
</script>
The Importance of key
In v-for, it is strongly recommended to provide a unique key attribute for each loop item, which helps Vue update the list efficiently.
Example
<!-- Use id as the key (recommended) -->
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
Other Extensions
Vue3 Built-in Directives