Vue 中 Element UI 的 el-table 组件实现动态表头和内容

在 Vue 中使用 Element UI 的 el-table 组件时,为了实现动态表头(包括第一层表头及其下的嵌套表头或子表头)。需要后端返回的数据结构能够体现表头层级关系以及对应的数据结构相匹配。这样的数据通常是一个嵌套数组,每个表头单元可能包含自身的列信息以及它的子表头和相关数据。

<template>
  <el-table :data="tableData">
    <el-table-column v-for="(header, index) in headers" :key="index" :label="header.title" :props="header.key || null">
      <el-table-column v-if="header.children" v-for="(subHeader, subIndex) in header.children" :key="`${index}-${subIndex}`" :label="subHeader.title" :props="subHeader.key">
        <!-- 显示子表头对应的数据 -->
        <template slot-scope="{ row }">
          {
   {
    row[subHeader.key] }}
        </template>
        <!-- 如果还有更深的层级,继续递归 -->
        <!-- ... -->
      </el-table-column>
      <!-- 对于没有子表头的一级列,直接显示数据 -->
      <template slot-scope="{ row }" v-else>
        {
   {
    row[header.key] }}
      </template>
    </el-table-column>
  </el-table>
</template>

<script>
export default {
   
  data() {
   
    return {
   
      tableData: [  
        {
   
          "field1_1": "数据项1-1",
          "field1_2_1": "数据项1-2-1",
          "field1_2_2": "数据项1-2-2",
          "field2": "数据项2"
        },
      ],
      headers: [  
        {
   
          "title": "一级表头1",
          children: [
            {
   
              "title": "二级表头1-1",
              "key": "field1_1"
            },
            {
   
              "title": "二级表头1-2",
              "children": [
                {
   
                  "title": "三级表头1-2-1",
                  "key": "field1_2_1"
                },
                {
   
                  "title": "三级表头1-2-2",
                  "key": "field1_2_2"
                }
              ]
            }
          ]
        },
        {
   
          "title": "一级表头2",
          "key": "field2"
        }
      ],
    };
  },
  created() {
   

  },
};
</script>

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-18 18:02:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-18 18:02:02       100 阅读
  3. 在Django里面运行非项目文件

    2024-01-18 18:02:02       82 阅读
  4. Python语言-面向对象

    2024-01-18 18:02:02       91 阅读

热门阅读

  1. 机器学习在产品质量控制中的具体应用是什么

    2024-01-18 18:02:02       72 阅读
  2. Easypoi word 模板导出问题

    2024-01-18 18:02:02       56 阅读
  3. Django密码修改和重置视图

    2024-01-18 18:02:02       61 阅读
  4. K8s面试题——情景篇

    2024-01-18 18:02:02       67 阅读