在 Vue.js v2.x 中使用 v-for 指令时如何指定范围的起始值?

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

我正在努力打印出用户可能在 Vue.js 中点击寻呼机组件的页码。我看到文档清楚地说 v-for 可以用于一个范围:

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

https://vuejs.org/v2/guide/list.html#v-for-with-a-Range

无论如何我还没有找到指定 n 的起始值。好像是从1开始,递增1直到10。

n 是否可以从 5 开始?

我似乎需要创建一个方法或计算 属性 来 return 我想要迭代的精确值的数组来代替静态 10。

还有人有其他想法吗?

无法在 n 开始 v-for

但是,从偏移量开始非常简单,只需将偏移量添加到您的值,然后在达到最大值时停止。

<div>
  <template v-for="n in max">
    <span v-if="n + offset <= max">{{ n + offset }} </span>
  </template>
</div>

如果您需要更多控制权,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;
    }

一种方法是定义您自己的辅助函数来生成序列:

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是起始位置,y是后续数字的个数。

所以这个...

Array(6).fill(5).map((x, y) => x + y)

你应该像[5, 6, 7, 8, 9, 10]这样的数组来遍历。

我认为这应该是一个更有效的答案。