How to Use v-for in Vue: Simple Looping Guide
Use the
v-for directive in Vue to loop over arrays or objects and render elements for each item. The syntax is v-for="(item, index) in items", where items is your data source and item is each element in the loop.Syntax
The v-for directive repeats an element or component for each item in a list. You write it as v-for="(item, index) in items", where:
- item: the current element in the list
- index: the current position (optional)
- items: the array or object you want to loop over
This directive must be used on an element inside your Vue template.
vue
<ul> <li v-for="(item, index) in items" :key="index">{{ item }}</li> </ul>
Output
<ul>
<li>First item</li>
<li>Second item</li>
<li>Third item</li>
</ul>
Example
This example shows how to use v-for to display a list of fruits. Each fruit is shown as a list item.
vue
<template>
<div>
<h2>Fruit List</h2>
<ul>
<li v-for="(fruit, index) in fruits" :key="index">{{ index + 1 }}. {{ fruit }}</li>
</ul>
</div>
</template>
<script setup>
import { ref } from 'vue'
const fruits = ref(['Apple', 'Banana', 'Cherry'])
</script>Output
<h2>Fruit List</h2>
<ul>
<li>1. Apple</li>
<li>2. Banana</li>
<li>3. Cherry</li>
</ul>
Common Pitfalls
Common mistakes when using v-for include:
- Not providing a unique
:keyattribute, which helps Vue track elements efficiently. - Using the same variable name inside and outside the loop, causing confusion.
- Trying to use
v-foron a component without a proper:key, leading to rendering bugs.
Always add a unique :key when looping, preferably a unique id if available.
vue
<!-- Wrong: missing key --> <ul> <li v-for="item in items">{{ item }}</li> </ul> <!-- Right: with key --> <ul> <li v-for="item in items" :key="item.id">{{ item.name }}</li> </ul>
Quick Reference
| Usage | Description |
|---|---|
| v-for="item in items" | Loop over an array named items |
| v-for="(item, index) in items" | Access item and its index |
| v-for="(value, key) in object" | Loop over object properties |
| :key="uniqueId" | Provide a unique key for each item |
| v-for on components | Use with :key to avoid rendering issues |
Key Takeaways
Use
v-for to loop over arrays or objects in Vue templates.Always provide a unique
:key attribute for each item in the loop.You can access the current item and its index using
(item, index) syntax.Avoid reusing variable names inside and outside the loop to prevent confusion.
Use
v-for on components carefully with proper keys to ensure correct rendering.