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>

运行结果:

相关推荐
一路向前的月光44 分钟前
Vue2中的监听和计算属性的区别
前端·javascript·vue.js
长路 ㅤ   1 小时前
vue-live2d看板娘集成方案设计使用教程
前端·javascript·vue.js·live2d
Fan_web1 小时前
jQuery——事件委托
开发语言·前端·javascript·css·jquery
Jiaberrr2 小时前
Element UI教程:如何将Radio单选框的圆框改为方框
前端·javascript·vue.js·ui·elementui
安冬的码畜日常4 小时前
【D3.js in Action 3 精译_029】3.5 给 D3 条形图加注图表标签(上)
开发语言·前端·javascript·信息可视化·数据可视化·d3.js
太阳花ˉ4 小时前
html+css+js实现step进度条效果
javascript·css·html
john_hjy4 小时前
11. 异步编程
运维·服务器·javascript
风清扬_jd5 小时前
Chromium 中JavaScript Fetch API接口c++代码实现(二)
javascript·c++·chrome
yanlele5 小时前
前瞻 - 盘点 ES2025 已经定稿的语法规范
前端·javascript·代码规范