[英]How can I specify the starting value for a range when using the v-for directive in Vue.js v2.x?
I'm working on printing out the page numbers a user may click on for a pager component in Vue.js.我正在打印出用户可以为 Vue.js 中的寻呼机组件单击的页码。 I see that the docs clearly say v-for can be used for a range:
我看到文档清楚地说 v-for 可以用于一个范围:
v-for can also take an integer.
v-for 也可以取整数。 In this case it will repeat the template that many times.
在这种情况下,它将多次重复模板。
<div> <span v-for="n in 10">{{ n }} </span> </div>
Result:
结果:
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Per https://v2.vuejs.org/v2/guide/list.html#v-for-with-a-Range根据https://v2.vuejs.org/v2/guide/list.html#v-for-with-a-Range
I have not found anyway to specify the starting value for n.反正我还没有找到指定 n 的起始值。 It seems that it starts at 1 and increments by 1 until 10.
它似乎从 1 开始并以 1 递增直到 10。
Is there anyway to start n at, say, 5?无论如何要从 5 开始?
It almost seems like I'll need to create a method or computed property that will return an array of the exact values I want iterated in place of the static 10.似乎我需要创建一个方法或计算属性,它将返回一个包含我想要迭代的确切值的数组来代替静态 10。
Anyone have any other thoughts?有人有其他想法吗?
There is no way to start a v-for
at n .没有办法在n开始
v-for
。
However, starting at an offset is as simple as adding the offset to your value and then stopping when you hit max.但是,从偏移量开始就像将偏移量添加到您的值一样简单,然后在达到最大值时停止。
<div>
<template v-for="n in max">
<span v-if="n + offset <= max">{{ n + offset }} </span>
</template>
</div>
If you need more control, a computed
property is most definitely the way to go, as it will provide you full control over whatever you're iterating over.如果您需要更多控制,那么
computed
属性绝对是您的最佳选择,因为它可以让您完全控制您正在迭代的任何内容。
<div>
<span v-for="n in computedArr">{{ n }} </span>
</div>
computed: {
computedArr() {
let arr = [];
for (var i = this.offset; i <= this.max; i++)
arr[i] = i;
return arr;
}
One way is to define your own helper function to generate the sequence:一种方法是定义自己的辅助函数来生成序列:
Vue.prototype.$range = function *(start, end, step = 1) { for (let i = start; i <= end; i += step) { yield i } } new Vue({ el: '#app' })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.js"></script> <div id="app"> <div v-for="i of $range(5, 10)"> {{ i }} </div> </div>
<div-for="index in Array(y).fill(x).map((x, y) => x + y)" :key="index">{{ index }}</div>
x
is the start position and y
is the count of subsequent numbers. x
是起始位置, y
是后续数字的计数。
so this...所以这...
Array(6).fill(5).map((x, y) => x + y)
will should you an array like [5, 6, 7, 8, 9, 10]
to traverse.你应该像
[5, 6, 7, 8, 9, 10]
这样的数组来遍历。
I think this should be a more efficient answer.我认为这应该是一个更有效的答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.