elementUI Table 合并第一列相同的数据

367 阅读1分钟

一、效果

image.png

二、实现

  1. 需要用到span-method属性,这个是用来将第n行到第n+n行合并的
  2. getMergeRowList方法,将数据中time字段相同值找出来,返回需要合并的行
<template>
  <div>
    <el-table :data="tableData" :span-method="spanMethod" border>
      <el-table-column prop="time" label="预警时间"> </el-table-column>
      <el-table-column prop="type" label="预警类型"> </el-table-column>
      <el-table-column prop="content" label="预警内容"> </el-table-column>
    </el-table>
  </div>
</template>
<script>
export default {
  data() {
    return {
      tableData: [
        {
          time: "2023/08/23 08:00:05",
          type: "营销客户风险",
          content: "预警内容123",
        },
        {
          time: "2023/08/23 08:00:05",
          type: "营销客户风险",
          content: "预警内容456",
        },
        {
          time: "2023/08/24 08:00:05",
          type: "营销客户风险",
          content: "预警内容789",
        },
        {
          time: "2023/08/24 08:00:05",
          type: "营销客户风险",
          content: "预警内容789",
        },
        {
          time: "2023/08/24 08:00:05",
          type: "营销客户风险",
          content: "预警内容789",
        },
        {
          time: "2023/08/24 08:00:05",
          type: "营销客户风险",
          content: "预警内容789",
        },
        {
          time: "2023/08/25 08:00:05",
          type: "营销客户风险",
          content: "预警内容789",
        },
        {
          time: "2023/08/25 08:00:05",
          type: "营销客户风险",
          content: "预警内容789",
        },
        {
          time: "2023/08/25 08:00:05",
          type: "营销客户风险",
          content: "预警内容789",
        },
      ],
    };
  },
  methods: {
    getMergeRowList(arr, key) {
      const mergeRowList = [];
      let concatOne = 0;
      arr.forEach((item, index) => {
        if (index === 0) {
          mergeRowList.push(1);
        } else {
          if (item[key] === arr[index - 1][key]) {
            // 第一列需合并相同内容的判断条件
            mergeRowList[concatOne] += 1;
            mergeRowList.push(0);
          } else {
            mergeRowList.push(1);
            concatOne = index;
          }
        }
      });
      console.log(mergeRowList);
      return mergeRowList;
    },
    spanMethod({ row, column, rowIndex, columnIndex }) {
      // 第一列
      if (columnIndex === 0) {
        const list = this.getMergeRowList(this.tableData, "time"); // 根据time字段获取哪些行需要合并
        const rowspan = list[rowIndex];
        const colspan = rowspan > 0 ? 1 : 0;
        return { rowspan, colspan };
      }
    },
  },
};
</script>