Vue v-for

Loop through arrays and objects in Vue

🔁 What is v-for?

The v-for directive renders a list of items by looping through arrays or objects. It's like a for-loop that creates multiple elements dynamically based on your data.


<!-- Simple v-for example -->
<ul>
  <li v-for="item in items">{{ item }}</li>
</ul>
                                    

Output:

  • Apple
  • Banana
  • Orange

v-for Basics

The v-for directive helps you display lists efficiently. You can loop through arrays, objects, and even numbers. It automatically updates when your data changes, making it perfect for dynamic content like shopping carts, user lists, or menu items.

📋

Array Loop

Loop through array items

<li v-for="fruit in fruits">
  {{ fruit }}
</li>
🔢

With Index

Access item index

<li v-for="(item, index) in items">
  {{ index }}: {{ item }}
</li>
🗂️

Object Loop

Loop through object properties

<li v-for="(value, key) in user">
  {{ key }}: {{ value }}
</li>
🔑

Key Attribute

Unique identifier for items

<li v-for="item in items" 
    :key="item.id">
  {{ item.name }}
</li>

🔹 Looping Through Arrays

Display a list of items from an array:

<template>
  <div>
    <h3>My Favorite Fruits</h3>
    <ul>
      <li v-for="fruit in fruits" :key="fruit">
        {{ fruit }}
      </li>
    </ul>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const fruits = ref(['Apple', 'Banana', 'Orange', 'Mango'])
</script>

Output:

My Favorite Fruits

  • Apple
  • Banana
  • Orange
  • Mango

🔹 Using Index in v-for

Access the index position of each item:

<template>
  <div>
    <h3>Numbered List</h3>
    <ul>
      <li v-for="(color, index) in colors" :key="index">
        {{ index + 1 }}. {{ color }}
      </li>
    </ul>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const colors = ref(['Red', 'Green', 'Blue'])
</script>

Output:

Numbered List

  • 1. Red
  • 2. Green
  • 3. Blue

🔹 Looping Through Objects

Display object properties using v-for:

<template>
  <div>
    <h3>User Information</h3>
    <ul>
      <li v-for="(value, key) in user" :key="key">
        <strong>{{ key }}:</strong> {{ value }}
      </li>
    </ul>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const user = ref({
  name: 'John Doe',
  age: 25,
  email: '[email protected]'
})
</script>

Output:

User Information

🔹 The :key Attribute

Always use :key to help Vue track each item uniquely:

<template>
  <div>
    <h3>Product List</h3>
    <div v-for="product in products" :key="product.id">
      <p>{{ product.name }} - ${{ product.price }}</p>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const products = ref([
  { id: 1, name: 'Laptop', price: 999 },
  { id: 2, name: 'Mouse', price: 25 },
  { id: 3, name: 'Keyboard', price: 75 }
])
</script>

Output:

Product List

Laptop - $999

Mouse - $25

Keyboard - $75

🧠 Test Your Knowledge

Why should you always use :key with v-for?