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

Vue中v-for循环实现表格动态rowspan渲染问题

车手多关联车队的表格渲染解决方案

需求说明

需要渲染表格实现:

  • 每位车手可关联1个或多个车队
  • position(排名)和points(积分)仅在对应车手的第一行显示,且根据车队数量设置rowspan
  • 每一行展示一个车队的名称与编号

问题分析

原代码仅对车手进行循环,未处理每个车手对应的多个车队,导致无法正确渲染多行车队信息。需要通过嵌套循环,针对每个车手的车队生成对应行,并控制position和points单元格的显示逻辑。

修正后的代码实现

Template部分

<template>
  <table>
    <!-- 表头部分 -->
    <thead>
      <tr>
        <th>排名</th>
        <th>车队编号</th>
        <th>车队名称</th>
        <th>积分</th>
      </tr>
    </thead>
    <tbody>
      <!-- 循环每个车手 -->
      <template v-for="driver in standings" :key="driver.position">
        <!-- 循环车手的每个车队 -->
        <tr v-for="(team, idx) in driver.teams" :key="team.id">
          <!-- 仅在第一个车队行显示排名,设置rowspan -->
          <td v-if="idx === 0" :rowspan="getRowspan(driver)">
            {{ driver.position }}
          </td>
          <!-- 车队编号 -->
          <td>{{ team.id }}</td>
          <!-- 车队名称 -->
          <td>{{ team.name }}</td>
          <!-- 仅在第一个车队行显示积分,设置rowspan -->
          <td v-if="idx === 0" :rowspan="getRowspan(driver)">
            {{ driver.points }}
          </td>
        </tr>
      </template>
    </tbody>
  </table>
</template>

Script部分(TypeScript)

<script setup lang="ts">
// 定义数据类型(根据实际数据结构调整)
interface Team {
  id: string | number;
  name: string;
}

interface DriverStanding {
  position: number;
  points: number;
  teams: Team[];
}

// 假设 standings 是你的数据源
const standings: DriverStanding[] = [
  // 示例数据,替换为实际数据
  {
    position: 1,
    points: 150,
    teams: [
      { id: "F01", name: "奔驰车队" },
      { id: "F03", name: "红牛车队" }
    ]
  },
  {
    position: 2,
    points: 120,
    teams: [{ id: "F02", name: "法拉利车队" }]
  }
];

// 计算当前车手的车队数量,用于设置rowspan
const getRowspan = (driver: DriverStanding): number => {
  return driver.teams.length;
};
</script>

关键逻辑说明

  1. 嵌套循环:通过两层循环,先遍历车手,再遍历车手的每个车队,为每个车队生成一行表格
  2. rowspan控制:仅在车手的第一个车队对应的行中渲染position和points单元格,并设置rowspan为车队总数,实现跨行合并
  3. 条件渲染:使用v-if="idx === 0"控制只有第一行显示排名和积分,后续行仅展示车队信息

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 08:52:23