Javascript Vue Js - 通过 v-for 循环 X 次(在一个范围内)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44617484/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Vue Js - Loop via v-for X times (in a range)
提问by MikeCaine
How can I repeat a loop via v-forX (e.g. 10) times?
如何通过v-forX(例如 10)次重复循环?
// 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.
但是 vue 从哪里知道对象的来源呢?如果我像文档说的那样渲染它,我会得到项目和项目的数量,但没有内容。
回答by Dov Benyomin Sohacheski
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 Documentationfor more information.
您还可以查看官方文档以获取更多信息。
回答by MikeCaine
I have solved it with Dov Benjamin's help like that:
我已经在 Dov Benjamin 的帮助下解决了这个问题:
<ul>
<li v-for="(n,index) in 2">{{ object.price }}</li>
</ul>
And another method, for both V1.x and 2.x of vue.js
另一种方法,适用于 v1.x 和 2.x 的 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)
}
}
回答by NickGreen
You can use the native JS slice method:
你可以使用原生的 JS 切片方法:
<div v-for="item in shoppingItems.slice(0,10)">
<div v-for="item in shoppingItems.slice(0,10)">
The slice() method returns the selected elements in an array, as a new array object.
slice() 方法将数组中选定的元素作为新的数组对象返回。
Based on tip in the migration guide: https://vuejs.org/v2/guide/migration.html#Replacing-the-limitBy-Filter
基于迁移指南中的提示:https: //vuejs.org/v2/guide/migration.html#Replace-the-limitBy-Filter
回答by abbaf33f
I had to add parseInt()to tell v-for it was looking at a number.
我不得不添加parseInt()告诉 v-因为它正在查看一个数字。
<li v-for="n in parseInt(count)" :key="n">{{n}}</li>
<li v-for="n in parseInt(count)" :key="n">{{n}}</li>
回答by besthost
The same goes for v-for in range:
v-for in range 也是如此:
<li v-for="n in 20 " :key="n">{{n}}</li>
<li v-for="n in 20 " :key="n">{{n}}</li>
回答by tdhulster
回答by Abdullah Pariyani
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" :key="item">
{{item}}
</li>
</ul>

