v-for
v-for repeats an element once for every item in a list, an object or a range.
In this page:
Syntax
<li v-for="item in items" :key="item.id">{{ item }}</li>
<li v-for="(item, index) in items" :key="index">{{ index }}: {{ item }}</li>
v-for
Write v-for="item in items" to loop over arrays, use (item, index) for the position, and (value, key) for object properties. A number loops that many times starting at 1. Always add a key so Vue can track items when the list changes.
Note:
Use a unique id, not the index, as the key when items can be reordered.
Example: v-for
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app">
<ul>
<li v-for="(fruit, i) in fruits" :key="fruit">{{ i + 1 }}. {{ fruit }}</li>
</ul>
<p v-for="(v, k) in person" :key="k">{{ k }} = {{ v }}</p>
<span v-for="n in 3" :key="n">[{{ n }}]</span>
</div>
<script>
Vue.createApp({
data() { return { fruits: ["apple", "banana", "cherry"], person: { name: "Ada", role: "engineer" } }; },
}).mount("#app");
</script>
</body>
</html>
<!-- Output:
Rendered: 1. apple2. banana3. cherryname = Adarole = engineer[1][2][3]
-->
Live Example
Related Topics
Common Mistakes
- Missing the key attribute
- Using the array index as key for reorderable lists
- Mutating arrays in ways Vue cannot detect
Chapter Summary
- item in items loops arrays
- (item, index) gives the position
- Objects give value, key
- Always provide a key
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: