Vue v-for Directive

Vue Tutorial

🔁 Vue v-for Directive

In Vue.js, the Vue v-for Directive is used for list rendering.

It allows you to loop through arrays, objects, or ranges and render elements dynamically.


 What is Vue v-for Directive?

v-for repeats an element or component for each item in a data source.

<li v-for="item in items">{{ item }}</li>

 Basic Syntax

v-for="(item, index) in list"
  • item → current element

  • index → position (optional)


 Example 1: Looping Through an Array


 


 Example 2: Looping Through Objects

<ul>
<li v-for="(value, key) in user" :key="key">
{{ key }} : {{ value }}
</li>
</ul>
data() {
return {
user: {
name: "Amit",
age: 22,
city: "Delhi"
}
}
}

 Example 3: Looping Through an Array of Objects

<tr v-for="user in users" :key="user.id">
<td>{{ user.name }}</td>
<td>{{ user.email }}</td>
</tr>
data() {
return {
users: [
{ id: 1, name: "Rahul", email: "rahul@mail.com" },
{ id: 2, name: "Neha", email: "neha@mail.com" }
]
}
}

 Example 4: Using v-for with <template>

Render multiple elements per item.

<template v-for="item in items" :key="item.id">
<h3>{{ item.title }}</h3>
<p>{{ item.desc }}</p>
</template>

 Example 5: Looping with a Number (Range)

<p v-for="n in 5" :key="n">
Count: {{ n }}
</p>

 The key Attribute (Very Important ⚠️)

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

Why key?

  • Improves performance

  • Helps Vue track element identity

  • Prevents rendering bugs

✔ Use unique IDs
❌ Avoid using index if possible


v-for with Components

<user-card
v-for="user in users"
:key="user.id"
:user="user"
/>

v-for + v-if (Avoid ❌)

❌ Bad practice:

<li v-for="item in items" v-if="item.active">...</li>

✔ Correct approach:

computed: {
activeItems() {
return this.items.filter(item => item.active)
}
}
<li v-for="item in activeItems" :key="item.id">...</li>

 Common Use Cases

  • Displaying lists

  • Tables

  • Menus

  • Cards

  • Repeating components


 Summary Table

Use Case Syntax
Array v-for="item in items"
Object v-for="(value, key) in obj"
Index v-for="(item, index) in items"
Range v-for="n in 5"
Component v-for="user in users"

 Conclusion

The v-for directive is essential for building dynamic lists and components in Vue.
Using key properly and avoiding v-if inside v-for will keep your app fast and bug-free.

You may also like...