首页 > 解决方案 > 如何在 Element UI 表格中显示嵌套单元格?

问题描述

我正在使用元素 UI。我有需要在表格中显示的嵌套数据。我无法理解如何显示嵌套数据的问题。

这是我的代码:

 <el-table :data="tableData" stripe border>
  <el-table-column width="170" prop="id"></el-table-column>
  <el-table-column width="170">
    <template slot-scope="scope">
    <!-- -->
    </template>
  </el-table-column>

 </el-table>

数据部分:

  tableData: [
   {
   "id":1,
   "nested": [{"name": "mike"}, {"name": "piter"}]
   },
   {
   "id":2,
   "nested": [{"name": "maria"}, {"name": "anna"}]
   },      
  ]

  };

https://jsfiddle.net/3nhb79qc/

我想显示它是这样的:在此处输入图像描述

标签: vue.jselement-ui

解决方案


一种解决方案是在 Element UI Table 中使用 span-method

首先,使用计算方法扁平化您的数据结构:

computed: {
  expandData() {
    return this.tableData.reduce((a, c) => {
      const arr = c.nested.map(item => ({
        id: c.id,
        name: item.name
      }))
      a = a.concat(arr)
      return a

    }, [])
  }
},

那么您的数据将变为:

[
    {
        "id": 1,
        "name": "mike"
    },
    {
        "id": 1,
        "name": "piter"
    },
    {
        "id": 2,
        "name": "maria"
    },
    {
        "id": 2,
        "name": "anna"
    }
]

之后定义objectSpanMethod并使用它el-table

  objectSpanMethod({ row, column, rowIndex, columnIndex }) {
    if (columnIndex === 0) {
      if (rowIndex % 2 === 0) {
        return {
          rowspan: 2,
          colspan: 1
        };
      } else {
        return {
          rowspan: 0,
          colspan: 0
        };
      }
    }
  }

jsfiddle 上的演示


推荐阅读