You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue中按行分组条件包裹组件为div的实现方法

问题描述

我有一个结构如下的ref变量:

[ { "row": 1, "column": 1 }, { "row": 1, "column": 2 }, { "row": 1, "column": 3 }, { "row": 1, "column": 4 }, { "row": 1, "column": 5 }, { "row": 1, "column": 6 }, { "row": 2, "column": 1 }, { "row": 2, "column": 2 }, { "row": 2, "column": 3 }, { "row": 2, "column": 4 }, { "row": 2, "column": 5 }, { "row": 2, "column": 6 }, { "row": 3, "column": 1 }, { "row": 3, "column": 2 }, { "row": 3, "column": 3 }, { "row": 3, "column": 4 }, { "row": 3, "column": 5 }, { "row": 3, "column": 6 }, { "row": 4, "column": 1 }, { "row": 4, "column": 2 }, { "row": 4, "column": 3 }, { "row": 4, "column": 4 }, { "row": 4, "column": 5 }, { "row": 4, "column": 6 } ]

希望遍历该数组渲染Box组件,并将同一行的组件用<div class="row"></div>包裹。当前的循环方式是:

<Box v-for="(cell, index) in grid" :key="index"></Box>

请问如何实现按行分组包裹组件的需求?


解决方案

方法一:先对数据按行分组(推荐)

在组件的计算属性里将原数组按row字段分组,生成二维数组后再嵌套循环,这种方式逻辑清晰、性能更优:

<script setup>
import { ref, computed } from 'vue'

const grid = ref([/* 你的原数组内容 */])

// 按行分组,得到二维数组,每个子数组对应一行的单元格
const groupedGrid = computed(() => {
  const rowGroups = {}
  grid.value.forEach(cell => {
    if (!rowGroups[cell.row]) {
      rowGroups[cell.row] = []
    }
    rowGroups[cell.row].push(cell)
  })
  // 按行号排序后转成数组,保证渲染顺序正确
  return Object.values(rowGroups).sort((a, b) => a[0].row - b[0].row)
})
</script>

<template>
  <!-- 外层循环遍历每一行,包裹row容器 -->
  <div class="row" v-for="(rowCells, rowIndex) in groupedGrid" :key="rowIndex">
    <!-- 内层循环渲染当前行的所有Box组件 -->
    <Box v-for="(cell, cellIndex) in rowCells" :key="cell.column" :cell="cell"></Box>
  </div>
</template>

方法二:模板内直接判断换行(适合小型数据场景)

如果不想修改数据结构,可以在模板中通过判断当前单元格是否为该行第一个元素,来动态生成row容器,但这种方式会重复执行过滤逻辑,数据量大时性能较差:

<template>
  <template v-for="(cell, index) in grid" :key="index">
    <!-- 仅在当前单元格是该行第一个时,渲染row容器及该行所有组件 -->
    <div class="row" v-if="index === 0 || grid[index - 1].row !== cell.row">
      <Box v-for="rowCell in grid.filter(c => c.row === cell.row)" :key="rowCell.column" :cell="rowCell"></Box>
    </div>
  </template>
</template>

内容的提问来源于stack exchange,提问作者Lubomir Borisov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 15:33:17