element-ui table根据属性合并行

 

注意:需要根据属性进行排序

 

直接上代码:

<template>
  <el-table
    ref="table"
    :data="tableData"
    border
    :span-method="objectSpanMethod"
  >
    <el-table-column prop="project" label="检测项目"> </el-table-column>
    <el-table-column prop="standard" label="检测标准"> </el-table-column>
    <el-table-column prop="method" label="检测方法"> </el-table-column>
    <el-table-column prop="price" label="检测价格"> </el-table-column>
  </el-table>
</template>

 

export default {
  props: ["info"],
  setup(props, content) {

    const data = reactive({
      tableData: [],
      colSpanArr: [],
      rowIndexArr: [],
    });

    const getList = () => {
        // 请求数据
        getColSpanData("project", data.tableData);
    }

    const getColSpanData = (prop, datas) => {
      let colLength = 1;
      datas.forEach((element, index) => {
        if (index == 0) {
          // rowIndex开始合并的位置为0,合并单元格数量默认为1
          data.rowIndexArr.push(0);
          colLength = 1;
        } else {
          if (element[prop] == datas[index - 1][prop]) {
            // 当相邻两条数据相等时,rowspan+1,即colLength+1
            colLength += 1;
            // 当最后一条数据与倒数第2条不等式,在colSpanArr中push(1)
            if (index == datas.length - 1) {
              data.colSpanArr.push(colLength);
            }
          } else {
            //  相邻两条不等时push index和合并的长度
            data.colSpanArr.push(colLength);
            data.rowIndexArr.push(index);
            if (index == datas.length - 1) {
              data.colSpanArr.push(1);
            }
            colLength = 1;
          }
        }
      });
      data.rowIndexArr.push(datas.length);
      console.log(data.rowIndexArr, data.colSpanArr);
      //  结果分别是:
      //data.rowIndexArr:[0, 2, 5, 7, 9,10]
      //data.colSpanArr:[2, 3, 2, 2, 1]
    };

    const objectSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
      if (columnIndex === 0) {
        for (let i = 0; i < data.colSpanArr.length; i++) {
          //如果rowIndex和data.rowIndexArr[i]相等则开始合并,合并数量对应为data.colSpanArr[i]
          if (rowIndex === data.rowIndexArr[i]) {
            return {
              rowspan: data.colSpanArr[i],
              colspan: 1,
            };
          } else {
            if (
              rowIndex > data.rowIndexArr[i] &&
              rowIndex < data.rowIndexArr[i + 1]
            ) {
              return {
                //被合并行则返回rowspan: 0, colspan: 0,
                //这里被合并行为1,3,4,6,8
                rowspan: 0,
                colspan: 0,
              };
            }
          }
        }
      }
    };
  }
}

 

posted @ 2021-12-31 09:47  我若亦如风  阅读(561)  评论(0编辑  收藏  举报