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>

运行结果:

相关推荐
老毛肚13 小时前
jeecgboot vue 路由 拆分01
前端·javascript·typescript
西部荒野子14 小时前
Zustand 状态管理规范:别让轻量状态变成隐形通知风暴
前端·javascript
之歆14 小时前
Day04_ES6完全指南:从入门到精通的现代化JavaScript开发
前端·javascript·es6
触底反弹14 小时前
从数据结构到 Prompt 设计:前端工程师的 AI 时代进阶指南
javascript·人工智能·python
橘猫走江湖14 小时前
前端项目如何做 vibe coding
javascript·vue.js·架构
小新11015 小时前
vue架的网站修改端口
前端·javascript·vue.js
用户17335980753715 小时前
纯前端 PDF 处理避坑指南:5 个线上真实问题的解决方案
前端·javascript
陈_杨15 小时前
鸿蒙APP开发-带你走近分构App的分子数据
前端·javascript
Goodbye15 小时前
深入理解 JavaScript 变量提升(Hoisting)—— 从现象到原理
javascript