← Back to Vue.js Course | Chapter 2: Template Syntax | Lesson 5 of 7

v-for

v-for repeats an element once for every item in a list, an object or a range.

In this page:

  1. v-for
Syntax
markup
<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

markup
<!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
  1. Missing the key attribute
  2. Using the array index as key for reorderable lists
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.