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

蹲街弑〆低调 提交于 2019-12-03 04:02:25

问题


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.


回答1:


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>

You can also check the Official Documentation for more information.




回答2:


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

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

& a other method i searched & found

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)
     }
  }

Thanks Coders!

See ya




回答3:


You can use the native JS slice method:

<div v-for="item in shoppingItems.slice(0,10)">

The slice() method returns the selected elements in an array, as a new array object.

Based on tip in the migration guide: https://vuejs.org/v2/guide/migration.html#Replacing-the-limitBy-Filter




回答4:


I had to add parseInt() to tell v-for it was looking at a number.

<li v-for="n in parseInt(count)" :key="n">{{n}}</li>




回答5:


The same goes for v-for in range:

<li v-for="n in 20 " :key="n">{{n}}</li>




回答6:


In 2.2.0+, when using v-for with a component, a key is now required.

<div v-for="item in items" :key="item.id">

Source




回答7:


var itemArray = ["item1", "item2", "item3", "item4", "item4"]
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<ul>
  <li v-for="item in itemArray">
    {{item}}
  </li>
</ul>


来源:https://stackoverflow.com/questions/44617484/vue-js-loop-via-v-for-x-times-in-a-range

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!