Blog
Jul 26, 2019 - 7 MIN READ
Intro to Vue - Looping over Lists of Data

Intro to Vue - Looping over Lists of Data

Got data? Learn how to loop over it in Vue.

Jennifer Bland

Jennifer Bland

In almost every application you will find that you need to loop over data and display it on the webpage. A good example is a getting data from the backend, possibly filtering the results and showing this to the users. That data could be a list of products, or services or items in a shopping cart. In this lesson I will show you how to loop over lists using Vue's v-for directive. So let's get started.

v-for

v-for

Looping Over an Array

v-for
<ul>
    <li v-for="item in items">{{ item }}</li>
</ul>

Here is the data in our items array:

data: {
  return {
     items: ['Hammer', 'Circular Saw', 'Torque Wrench']
  };
}

When this code runs it creates an unordered list showing all 3 items. It will look like this.

Adding a Key

You can specify your own key which must be unique or you can use the $index that Vue creates automatically. The key is an optional second argument for the index of the current item. Let's update our example of looping over an array to include this index.

<ul>
    <li v-for="(item, $index) in items" :key="$index">{{ $index }} - {{ item }}</li>
</ul>

Looping Over an Object

v-for

Here is an object that lists states and their capitals. We will loop over this object.

capitals: {
      Arkansas: 'Little Rock',
      Illinois: 'Springfield',
      Kentucky: 'Frankfort',
      'New York': 'Albany'
}

Here is the code to loop over this capitals object and show list of capitals:

<ul>
    <li v-for="value in capitals">{{ value }}</li>
</ul>

This is the output:

Looping Over an Object - getting key

:keyv-for
<ul>
    <li v-for="(value, key) in capitals" :key="key">{{ key }} - {{ value }}</li>
</ul>

This is the output:

Looping Over an Object - getting key and index

<ul>
    <li v-for="(value, key, index) in capitals" :key="key">{{ index }}. {{ key }} - {{ value }}</li>
</ul>

This is the output:

Get The Code

Click here to get the code

Conclusion

Follow me on Twitter