Looping through Number Ranges

Published on March 13, 2017 by

In this short lecture, I am going to show you how you can output a range of numbers with the v-for directive. By specifying a number as the expression, the template will be repeated that number of times. So if I wanted to output a list of the numbers from one to ten, I would give the current number an alias followed by the in keyword and the number ten.

<li v-for="n in 10"></li>

{{ n }}

What Vue.js does for us, is that it loops ten times and increments n by one for each iteration. And sure enough, we see a list containing the numbers from one to ten.

This syntax also enables you to access the loop index in exactly the same way as you have previously seen.

<li v-for="(n, index) in 10">{{ n }}</li>

Now that we have the loop index available, we could do something like outputting n multiplied with index. I will output both numbers as well as the result of the multiplication.

{{ n }} * {{ index }} = {{ n * index }}

And as you can see, we now have access to both the range of numbers and the loop index, and we can do with those whatever we please.

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!

3 comments on »Looping through Number Ranges«

  1. borio

    cool

  2. Odd Returnman

    Thanks!

  3. Hari Prasad

    very helpful one thanks a lot Bo Andersen

  4. Sinan

    When I use a real number in the loop as: it works.
    But if I try to get the number from a variable declared in data as: , it doesnt work.

Leave a Reply

Your e-mail address will not be published.