Episode 12 of 44
Looping with v-for
Render lists of data with v-for — loop through arrays and objects, use the key attribute, and access the index.
Looping with v-for
The v-for directive renders a list of elements by looping through an array or object. It is one of the most commonly used directives in Vue.
Looping Through an Array
<ul>
<li v-for="ninja in ninjas" :key="ninja.id">
{{ ninja.name }} - Rank: {{ ninja.rank }}
</li>
</ul>
data: {
ninjas: [
{ id: 1, name: 'Ryu', rank: 5 },
{ id: 2, name: 'Ken', rank: 3 },
{ id: 3, name: 'Yoshi', rank: 8 }
]
}
Accessing the Index
<li v-for="(ninja, index) in ninjas" :key="ninja.id">
{{ index + 1 }}. {{ ninja.name }}
</li>
The key Attribute
Always provide a unique :key when using v-for. Vue uses the key to track each element and efficiently update the DOM when the list changes.
| Key Usage | Result |
|---|---|
| No key | Vue reuses elements by position — can cause bugs with stateful elements |
:key="index" | Better, but breaks when items are reordered |
:key="item.id" | Best — unique, stable identifier |
Looping Through Objects
<div v-for="(value, key) in person" :key="key">
{{ key }}: {{ value }}
</div>
data: {
person: { name: 'Shaun', age: 25, job: 'Developer' }
}
// Output: name: Shaun, age: 25, job: Developer
v-for with v-if
<!-- Not recommended — v-for has higher priority than v-if -->
<li v-for="ninja in ninjas" v-if="ninja.rank > 3">
<!-- Better — use a computed property to filter first -->
<li v-for="ninja in topNinjas">
computed: {
topNinjas() {
return this.ninjas.filter(n => n.rank > 3);
}
}
Key Takeaways
v-for="item in array"loops through arrays;(item, index)gives you the index- Always provide a unique
:key— use a stable ID, not the index - Avoid using
v-ifon the same element asv-for— use a computed property instead