Vue v-for Components

Vue v-for with Components

In previous chapters, we learned how to use v-for to repeat standard HTML elements.

However, the true power of Vue shines when you combine v-for with custom components!

This allows you to render a massive list of dynamic UI elements based on an array of data.


Rendering Components in a Loop

You can use the v-for directive directly on a custom component tag.

The syntax is exactly the same as using it on a standard <li> tag.

However, just looping the component won't pass the array data into it automatically.


Passing Loop Data as Props

To give each generated component its unique data, you must bind the loop variable to a prop.

This perfectly marries the concept of v-for with dynamic prop binding (:propName).

Component Loop Example:

<template>
  <h1>My Blog Posts</h1>
  

<!-- Looping through an array of objects --> <BlogPost v-for="post in posts" :key="post.id" :title="post.title" /> </template>

<script setup> import { ref } from 'vue' import BlogPost from './BlogPost.vue'

// An array of post objects from a simulated database const posts = ref([ { id: 1, title: 'Introduction to Vue' }, { id: 2, title: 'Mastering Components' }, { id: 3, title: 'Understanding Props' } ]) </script>


The Importance of the Key Attribute

Notice that we included :key="post.id" in the component loop above.

When using v-for on custom components, providing a key attribute is mandatory!

Components carry their own internal state, and without a unique key, Vue cannot track them properly during list updates.


Passing Entire Objects

If your array objects have a lot of properties, binding them one by one (:title, :author, :date) becomes tedious.

Instead, you can pass the entire object as a single prop!

<BlogPost v-for="post in posts" :key="post.id" :postData="post" />

The child component then simply accepts defineProps(['postData']).


Exercise 1 of 1

?

When you use v-for directly on a custom component tag, how do you pass the looped data into the component itself?