Looping through Number Ranges
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.
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!
3 comments on »Looping through Number Ranges«
cool
Thanks!
very helpful one thanks a lot Bo Andersen
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.