Vue v-for with Components
🔁 Vue v-for with Components
This is extremely common in real-world apps (cards, lists, tables, dashboards).
What Does Vue v-for with Components Mean?
Instead of looping over plain HTML elements, you loop over components.
Each loop iteration creates one component instance.
Basic Example
🧩 Parent Component
🧩 Child Component (UserCard.vue)
🔑 The key Attribute (VERY IMPORTANT ⚠️)
Why key?
-
Helps Vue track components efficiently
-
Prevents rendering bugs
-
Improves performance
✔ Always use a unique ID
❌ Avoid array index if possible
Passing Whole Object as Prop
Cleaner and scalable.
Using v-for with <template>
When you want multiple root elements per item.
📌 <template> does not render in DOM.
v-for with Events in Components
Child:
v-for + v-if with Components ❌
❌ Bad practice:
✔ Correct approach (computed):
Dynamic Component Lists
✔ Useful for dashboards & widgets
Common Use Cases
-
User cards
-
Product lists
-
Blog posts
-
Tables
-
Dashboards
-
Menus
Common Mistakes ❌
❌ Missing key
❌ Mutating props inside child
❌ Large logic inside template
❌ Using index as key unnecessarily
Best Practices ✅
✔ Always use :key
✔ Pass objects instead of many props
✔ Use computed for filtering
✔ Keep child components focused
✔ Use emits for actions
Summary Table
| Task | Pattern |
|---|---|
| Render components list | v-for="item in items" |
| Unique identity | :key="item.id" |
| Pass data | :item="item" |
| Handle actions | $emit() |
| Filter list | Computed |
🏁 Conclusion
Using v-for with components is the backbone of scalable Vue UIs.
Once you master this, you can build dynamic, reusable, and maintainable interfaces easily.
