Published:

Vue.js - Display a list of items with v-for

Other versions available:

This is a quick example to show how to display a list of items in Vue with the v-for directive.

The example simply renders an array of users as rows in a table with <tr v-for="user in users" :key="user.id">.

Here it is in action: (See on CodeSandbox at https://codesandbox.io/s/vuejs-display-a-list-of-items-with-v-for-plys5)


Example Vue component that renders the users array

The app component template contains some standard html for a heading and table, and inside the table the tr tag uses the v-for Vue directive to loop over the users array and render a table row for each user that includes the user name, email and role.

The app component contains the hardcoded users array that is rendered with the v-for directive in template. The users array is declared as a data property of the Vue component so the template can see it.

<template>
    <div class="container">
        <h3 class="p-3 text-center">Vue.js - Display a list of items with v-for</h3>
        <table class="table table-striped table-bordered">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Email</th>
                    <th>Role</th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="user in users" :key="user.id">
                    <td>{{user.firstName}} {{user.lastName}}</td>
                    <td>{{user.email}}</td>
                    <td>{{user.role}}</td>
                </tr>
            </tbody>
        </table>
    </div>    
</template>

<script>
export default {
    data() {
        return {
            users: [
                { firstName: 'Frank', lastName: 'Murphy', email: '[email protected]', role: 'User' },
                { firstName: 'Vic', lastName: 'Reynolds', email: '[email protected]', role: 'Admin' },
                { firstName: 'Gina', lastName: 'Jabowski', email: '[email protected]', role: 'Admin' },
                { firstName: 'Jessi', lastName: 'Glaser', email: '[email protected]', role: 'User' },
                { firstName: 'Jay', lastName: 'Bilzerian', email: '[email protected]', role: 'User' }
            ]
        };
    }
};
</script>


Render an array of objects with index instead of id

If you have an array of objects that don't have a unique property (e.g. id) that you can use for the :key attribute, it's possible to use the item index which is provided by the v-for directive.

This is how the above v-for would look using the item index instead of the id as the key prop:

<tr v-for="(user, index) in users" :key="index">
    ...
</tr>

 

Subscribe or Follow Me For Updates

Subscribe to my YouTube channel or follow me on Twitter or GitHub to be notified when I post new content.

 


Supported by