Looping through List in VueJS

Let’s move further and see how we can loop through a list in VueJS.

Problem: You want to loop through and print list in VueJS, List can be of numbers, arrays, and Objects.

Solution:

#1 Loop through a List of Numbers
Here is how you can loop through a list of numbers.

Assuming you have initiated a new Vue Instance and have associated it with the element of id app

    <div id="app">
        <ul>
            <li v-for="n in 5">{{n}}</li>
        </ul>
    </div>

   var app = new Vue({
        el: '#app',
  });

Notice the new directive v-for, we can loop through a list using v-for directive and specifying the item in items where an item is the current iteration and items are the total number of items in the list.

#2 Loop through a List of Array Elements
Next, let’s loop over a list of array elements

<ul>
      <li v-for="n in countdown">{{n}}</li>
</ul>

Here countdown is an array defined inside the data property of out Vue instance.

    var app = new Vue({
        el: '#app',
        data: {
            countdown: [5, 4, 3, 2, 1]
        }
    });

#3 Loop through a List of Array with Index Notation

You can also make use of an optional second argument supported in v-for to fetch the index of the current item, v-for="(item, index) in items"

For example

<ul>
     <li v-for="(fruit, i) in fruits">{{i}} - {{fruit}}</li>
</ul>
var app = new Vue({
        el: '#app',
        data: {
            fruits: ["Apple", "Banana", "Orange", "Mango", "Grapes"]
        }
 });

This will print the list of fruits along with its index position in the array.

#4 Loop through an Object Properties

You can also loop through the list of properties defined in the javascript object.

<ul>
     <li v-for="(value, key, index) in profile">{{key}} - {{value}}</li>
</ul>
    var app = new Vue({
        el: '#app',
        data: {
            profile : {
                name : 'Tushar',
                age : '31',
                degree : 'Masters',
                position : 'Full Stack Developer'
            }
        }
    });

To iterate through the properties of an object v-for directive has the following order v-for="(value, key, index)

That’s all about looping using v-for directive in VueJS.

Practice Excercises

  1. Loop through an Array of objects, and output the object properties in a table. (CodePen Solution Link
tgugnani: Web Stuff Enthusiast.