'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. I see that the docs clearly say v-for can be used for a range:
v-for can also take an integer. 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
Per https://vuejs.org/v2/guide/list.html#v-for-with-a-Range
I have not found anyway to specify the starting value for n. It seems that it starts at 1 and increments by 1 until 10.
Is there anyway to start n at, say, 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.
Anyone have any other thoughts?
Solution 1:[1]
There is no way to start a v-for
at n.
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.
<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;
}
Solution 2:[2]
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>
Solution 3:[3]
<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.
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.
I think this should be a more efficient answer.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Decade Moon |
Solution 3 | Pinch |