Accessing the Loop Index

Published on March 13, 2017 by

By slightly modifying the syntax within the v-for directive, we can gain access to the current index of the loop. The index starts at zero and is incremented by one for each iteration. To show this, I have reused part of the example from the previous post and have added room for outputting the loop index within the employees table.

To access the loop index, we need to modify the part of the v-for directive that contains the alias for the current iteration’s item. We need to enclose this part within parenthesis, first of all.

<tr v-for="(employee) in employees">

Then, following the alias, we need to add a comma and an alias with which we wish to refer to the loop index. In this case, I will name it index, but you could choose anything you’d like.

<tr v-for="(employee, index) in employees">

With this, I can simply output the index through string interpolation.

<td>{{ index }}</td>

Running the code, we should see 0, 1 and 2 being output within the table, and indeed we do.

Later in the series, we will take a look at using this loop index to add a background color to every second row of this table, but for now, just know that if you ever need to access the current index of the loop iteration, then this is how you can do it.

Featured

Learn Vue.js today!

Take an online course and become an Vue.js champion!

Here is what you will learn:

  • How to build advanced Vue.js applications (including SPA)
  • How Vue.js works under the hood
  • Communicating with services through HTTP
  • Managing state of large applications with Vuex
  • ... and much more!
Vue.js logo
Author avatar
Bo Andersen

About the Author

I am a back-end web developer with a passion for open source technologies. I have been a PHP developer for many years, and also have experience with Java and Spring Framework. I currently work full time as a lead developer. Apart from that, I also spend time on making online courses, so be sure to check those out!

Leave a Reply

Your e-mail address will not be published.