v-for 循环数组的某一部分

方法一:使用slice()方法

代码:

<template>
  <div>
    <!--循环前三个元素-->
    <span v-for="(item, index) in arr.slice(0, 3)" :key="index + 'a'">{{ item }}</span> <br>
    <!--循环前第六个到第九个元素-->
    <span v-for="(item, index) in arr.slice(5, 9)" :key="index + 'b'">{{ item }}</span> <br>
    <!--循环后三个元素-->
    <span v-for="(item, index) in arr.slice(-3)" :key="index + 'c'">{{ item }}</span>
  </div>
</template>

<script>
export default {
  data() {
    return {
      arr: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    }
  }
}
</script>

运行结果:

请添加图片描述

方法二:使用filter()方法

代码:

<template>
  <div>
    <!--只循环偶数-->
    <span v-for="(item, index) in evenNumbers" :key="index">{{ item }}</span>
  </div>
</template>

<script>
export default {
  data() {
    return {
      arr: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    }
  },
  computed: {
    evenNumbers() {
      return this.arr.filter(item => item % 2 === 0)
    }
  }
}
</script>

运行结果:

请添加图片描述

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用Vue3的响应式数据和computed属性来实现这个功能。 首先,定义一个响应式的数组和一个当前选中的索引,以及一个computed属性来根据当前选中的索引计算出当前展示的数组。 ```javascript <template> <div> <div v-for="num in currentNums" :key="num">{{num}}</div> <button @click="prev">上一个</button> <button @click="next">下一个</button> </div> </template> <script> import { reactive, computed } from 'vue' export default { setup() { const nums = reactive([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) let currentIndex = 0 const currentNums = computed(() => { const start = currentIndex const end = Math.min(currentIndex + 10, nums.length) return nums.slice(start, end) }) const prev = () => { if (currentIndex > 0) { currentIndex-- } } const next = () => { if (currentIndex < nums.length - 1) { currentIndex++ } } return { currentNums, prev, next } } } </script> ``` 在模板中,使用v-for指令循环展示当前的数组。 在JavaScript代码中,使用reactive函数包装数组,使其成为响应式数据。定义一个currentIndex变量来记录当前选中的索引。使用computed属性根据currentIndex计算出当前展示的数组,slice函数用来截取数组一部分。prev和next函数分别用来往前和往后移动currentIndex变量,但要注意边界问题。 最后,限制数组长度不超过16,只需要在定义响应式数组时传入一个长度为16的空数组即可。 ```javascript const nums = reactive(new Array(16)) ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值