VueJS part 4: Rendering in loop

Kristijan
3 min readSep 21, 2023

Introduction

Recently, I started learning VueJS, and this article is part of the series of my notes while learning it. In this one, I am covering how to use loops to render content.

Vue logo

Directive v-for

Displaying lists is quite common when building web applications. The problem with it is that most often we don’t know ahead of time how many items there are. And even if we did, repeating all that content manually would be crazy. That is why Vue has the v-for directive. You add it to the element, give it an array of items, and it will render content inside of it for each array element.

v-for example

For example, let’s display a list of people with their first name, last name, and dob. Therefore, we need that list in the application data.

{
data() {
return {
people: [
{
id: 1,
firstName: "John",
lastName: "Doe",
dob: "01-01-1980"
},
{
id: 1,
firstName: "Johny",
lastName: "Doe",
dob: "01-01-1980"
},
{
id: 1,
firstName: "James",
lastName: "Doe",
dob: "01-01-1980"
}
]
}
},
methods: {}
}

Then to display it in the HTML, it is just a matter of adding it to the v-for directive.

<ul>
<li v-for="person in people" >
<div>{{person.firstName}} {{person.lastName}} - {{person.dob}}</div>
</li>
</ul>

Using index in the loop

It is common to use a current index when looping through the array. And that is something that you can access with the v-for directive. In the code above, you can notice that I used syntax person in people. Other than person, the second argument you can use is index.

<li v-for="(person, index) in people" >
<div>{{index}}. {{person.firstName}} {{person.lastName}} - {{person.dob}}</div>
</li>

Key attribute

When displaying values in the HTML, Vue will update changed values. However, with the arrays, it is a bit tricky, and you can help Vue to know which elements are updated so they can be properly and efficiently…

--

--