Vue 3 - Display a list of items with v-for
Other versions available:
- Vue: Vue 2
- React: React
- Angular: Angular
- ASP.NET Core: Blazor WebAssembly
This is a quick example to show how to display a list of items in Vue 3 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 StackBlitz at https://stackblitz.com/edit/vue-3-display-a-list-of-items-with-v-for)
Example Vue 3 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 the template. The users array is created and returned by the Vue 3 setup()
method which makes it available to the template. The setup()
method runs before the component is created and serves as the entry point for Vue 3 components that are created with the new Composition API. The users
array is created as a reactive variable using the Vue 3 ref()
function.
For more info on the Vue 3 Composition API see https://v3.vuejs.org/guide/composition-api-introduction.html.
<template>
<div class="container">
<h3 class="p-3 text-center">Vue 3 - 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>
import { ref } from 'vue';
export default {
name: 'App',
setup() {
// make users variable reactive with the ref() function
const users = ref([
{ 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' }
]);
return {
users
};
}
}
</script>
Render an array in Vue 3 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>
Need Some Vue 3 Help?
Search fiverr for freelance Vue 3 developers.
Follow me for updates
When I'm not coding...
Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!