Vue v-for Directive
🔁 Vue v-for Directive
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.
Basic Syntax
-
item→ current element -
index→ position (optional)
Example 1: Looping Through an Array
Example 2: Looping Through Objects
Example 3: Looping Through an Array of Objects
Example 4: Using v-for with <template>
Render multiple elements per item.
Example 5: Looping with a Number (Range)
The key Attribute (Very Important ⚠️)
Why key?
-
Improves performance
-
Helps Vue track element identity
-
Prevents rendering bugs
✔ Use unique IDs
❌ Avoid using index if possible
v-for with Components
v-for + v-if (Avoid ❌)
❌ Bad practice:
✔ Correct approach:
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.
