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

方法一:使用slice()方法

代码:

html 复制代码
<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()方法

代码:

html 复制代码
<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>

运行结果:

相关推荐
巴博尔41 分钟前
UNIAPP中NVUE页面 动画
android·前端·javascript·ios·uni-app
猫头虎-前端技术1 小时前
JS 作用域与闭包:从变量提升到闭包陷阱的超详细解析
开发语言·javascript·云计算·bootstrap·ecmascript·openstack·perl
她说人狗殊途3 小时前
基于 vue-cli 创建
前端·javascript·vue.js
大家的林语冰4 小时前
Deno 2.8 正式发布,再次超越 Bun,史上最大的次版本升级诞生!
前端·javascript·node.js
影寂ldy4 小时前
C#数组的属性和方法(Clear / Copy / IndexOf )
开发语言·javascript·c#
Brave & Real4 小时前
小程序 const 在js中以及与同类的var和let之间的差异
javascript·微信小程序·小程序
米丘5 小时前
React 19.x 的 lazy 与 Suspense
前端·javascript·react.js
ZC跨境爬虫6 小时前
跟着 MDN 学CSS day_21:(图像溢出控制与表单元素样式定制)
前端·javascript·css·ui·交互
riuphan6 小时前
JavaScript 中的 this 关键字
javascript
掰头战士6 小时前
五分钟带你深入了解 this
javascript