el-table合并相同名称的列

el-table合并相同名称的列

html 复制代码
<template>
    <el-table
      :data="tableData"
      :span-method="objectSpanMethod"
      border
    >
      <el-table-column
        prop="name"
        label="名称"
        width="180"
      ></el-table-column>
      <el-table-column
        prop="category"
        label="类别"
        width="180"
      ></el-table-column>
      <el-table-column
        prop="date"
        label="日期"
      ></el-table-column>
    </el-table>
</template>

<script>
export default {
  data() {
    return {
      tableData: [
        { name: '产品A', category: '电子产品', date: '2023-01-01' },
        { name: '产品A', category: '电子产品', date: '2023-01-02' },
        { name: '产品A', category: '电子产品', date: '2023-01-03' },
        { name: '产品B', category: '办公用品', date: '2023-01-01' },
        { name: '产品B', category: '办公用品', date: '2023-01-02' },
        { name: '产品C', category: '家居用品', date: '2023-01-01' },
        { name: '产品D', category: '体育用品', date: '2023-01-01' },
        { name: '产品D', category: '体育用品', date: '2023-01-02' },
      ],
      // 存储需要合并的行信息
      spanArr: [],
      // 当前需要合并的行数
      position: 0
    };
  },
  mounted() {
    // 初始化时计算需要合并的行
    this.getSpanArr(this.tableData);
  },
  methods: {
    // 计算需要合并的行
    getSpanArr(data) {
      this.spanArr = [];
      this.position = 0;
      
      for (let i = 0; i < data.length; i++) {
        if (i === 0) {
          // 第一行默认需要合并1行
          this.spanArr.push(1);
          this.position = 0;
        } else {
          // 判断当前行与上一行是否相同
          if (data[i].name === data[i - 1].name) {
            // 如果相同,上一行的合并数加1
            this.spanArr[this.position] += 1;
            // 当前行合并数为0(被合并)
            this.spanArr.push(0);
          } else {
            // 如果不同,重新开始计算合并数
            this.spanArr.push(1);
            this.position = i;
          }
        }
      }
    },
    
    // 合并方法
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      // 只处理"名称"列的合并
      if (columnIndex === 0) {
        const _row = this.spanArr[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col
        };
      }
    }
  }
};
</script>