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>

运行结果:

相关推荐
时空无限10 分钟前
EFK 中使用 ruby 和 javascript 脚本去掉日志中颜色字符详解
linux·javascript·elk·ruby
噢,我明白了6 小时前
JavaScript 中处理时间格式的核心方式
前端·javascript
C_心欲无痕8 小时前
vue3 - 类与样式的绑定
javascript·vue.js·vue3
南山安10 小时前
Tailwind CSS:顺风CSS
javascript·css·react.js
千寻技术帮10 小时前
10422_基于Springboot的教务管理系统
java·spring boot·后端·vue·教务管理
栀秋66611 小时前
防抖 vs 节流:从百度搜索到京东电商,看前端性能优化的“节奏哲学”
前端·javascript
有意义11 小时前
深入防抖与节流:从闭包原理到性能优化实战
前端·javascript·面试
2503_9284115612 小时前
12.26 小程序问题和解决
前端·javascript·微信小程序·小程序
over69712 小时前
防抖与节流:前端性能优化的“双子星”,让你的网页丝滑如德芙!
前端·javascript·面试
red润12 小时前
手把手封装Iframe父子单向双向通讯功能
前端·javascript·vue.js