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

如何在Vue Element-Ui的el-table-column列中展示嵌套数组内容?

解决方案

这里分两种实现路径,匹配你不同的布局需求:

方案1:保留现有单行列布局,消除重复循环代码

适合你希望同一用户的所有cost数据仍放在同一行、同列单元格内的场景,只需要把重复的列配置抽成公共数组,循环渲染列即可:

步骤1:新增列配置项

在组件内定义你需要渲染的costData字段配置:

// 组件script部分新增
costColumnConfig = [
  { label: '服务名称', prop: 'serviceName', width: '160' },
  { label: '单次成本', prop: 'cost', width: '160' },
  { label: '总成本', prop: 'totalCost', width: '160' }
]

步骤2:模板循环渲染列

模板里直接循环配置生成列,无需重复编写循环逻辑:

<template>
  <el-table :data="tableData">
    <el-table-column prop="name" label="Name" width="120" />
    <el-table-column prop="surname" label="Surname" width="120" />
    <!-- 循环生成cost相关列,只写一次循环逻辑 -->
    <el-table-column
      v-for="column in costColumnConfig"
      :key="column.prop"
      :prop="`costData.${column.prop}`"
      :label="column.label"
      :width="column.width"
    >
      <template slot-scope="scope">
        <div v-for="(item, index) in scope.row.costData" :key="index">
          {{ item[column.prop] }}
        </div>
      </template>
    </el-table-column>
  </el-table>
</template>

注:原有代码存在逻辑错误,后两列的循环对象误写为scope.row.totalCost,实际应为scope.row.costData,上述代码已修正。

方案2:使用原生单元格渲染,无内部div循环

如果你希望每个costData项对应独立的表格行、所有值都在原生td内渲染,不需要单元格内部嵌套div循环,可以先通过计算属性扁平化原表格数据:

步骤1:新增扁平化计算属性

// 组件script部分新增
get flatTableData() {
  if (!this.tableData) return []
  return this.tableData.flatMap(user => {
    return user.costData.map(costItem => ({
      name: user.name,
      surname: user.surname,
      ...costItem
    }))
  })
}

步骤2:直接绑定扁平化数据,无需内部循环

<template>
  <!-- 绑定扁平化后的数据 -->
  <el-table :data="flatTableData">
    <el-table-column prop="name" label="Name" width="120" />
    <el-table-column prop="surname" label="Surname" width="120" />
    <el-table-column prop="serviceName" label="服务名称" width="160" />
    <el-table-column prop="cost" label="单次成本" width="160" />
    <el-table-column prop="totalCost" label="总成本" width="160" />
  </el-table>
</template>

这个方案完全没有单元格内部的自定义div,所有值都渲染在原生的表格单元格内,代码更简洁,性能也更好。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 00:09:04