How can I specify the starting value for a range when using the v-for directive in Vue.js v2.x?

2.1k views Asked by At

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://v2.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?

3

There are 3 answers

3
zcoop98 On BEST ANSWER

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.push(i);
      return arr;
    },
    ...
0
Decade Moon On

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>

0
Pinch On
 <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.