Vue Js - Loop via v-for X times (in a range)

How can I repeat a loop via v-for X (e.g. 10) times?

// want to repeat this (e.g.) 10 times

<ul>
  <li v-for="item in shoppingItems">
    {{ item.name }} - {{ item.price }}
  </li>
</ul>

The documentation shows:

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

// or 

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

// this doesn't work

<li v-for="item in 10">{{ item.price }}</li>

but from where does vue know the source of the objects? If I render it like the doc says, I get the number of items and items, but without content.


You can use an index in a range and then access the array via its index:

<ul>
  <li v-for="index in 10" :key="index">
    {{ shoppingItems[index].name }} - {{ shoppingItems[index].price }}
  </li>
</ul>

Note that this is 1-indexed: in the first iteration, index is 1, and in the second iteration, index is 2, and so forth.

You can also check the Official Documentation for more information.


I have solved it with Dov Benjamin's help like that:

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

Note that in this case, n is 1-indexed, and index is 0-indexed.

And another method, for both V1.x and 2.x of vue.js

Vue 1:

<p v-for="item in items | limitBy 10">{{ item }}</p>

Vue2:

// Via slice method in computed prop

<p v-for="item in filteredItems">{{ item }}</p>

computed: {
   filteredItems: function () {
     return this.items.slice(0, 10)
     }
  }