el-table 的合并单元格

190 阅读1分钟

关于el-table的使用或者在使用过程中产生的疑问

合并单元格

合并行

image.png

    <template>
  <el-table :data="tableData" border>
    <el-table-column prop="date" label="日期" width="150"> </el-table-column>
    <el-table-column prop="name" label="姓名" width="120"> </el-table-column>
    <el-table-column prop="province" label="省份" width="120">
    </el-table-column>
    <!-- 这块是重点 就是el-table-column 套 el-table-column-->
    <el-table-column label="详细地址" align="center">
      <el-table-column prop="city" label="市区" width="120"> </el-table-column>
      <el-table-column prop="address" label="地址" width="300">
      </el-table-column>
      <el-table-column prop="zip" label="邮编" width="120"> </el-table-column>
    </el-table-column>
    <el-table-column label="操作" width="100">
      <template slot-scope="scope">
        <el-button @click="handleClick(scope.row)" type="text" size="small">查看</el-button>
        <el-button type="text" size="small">编辑</el-button>
      </template>
    </el-table-column>
  </el-table>
</template>
  

合并列

image.png


 <el-table :data="tableData" border :span-method="spanMethod">
 ...
 </el-table>
 
 
 
    //合并单元格
    spanMethod({ row, column, rowIndex, columnIndex }) {
      //定义需要合并的列字段,有哪些列需要合并,就自定义添加字段即可 
      //注意下面的 tableData 是你的表格数据 要替换成你的字段名称
      const fields = ["name" ,"province"];
      // 当前行的数据
      const cellValue = row[column.property];
      // 判断只合并定义字段的列数据
      if (cellValue && fields.includes(column.property)) {
        const prevRow = this.tableData[rowIndex - 1]; //上一行数据
        let nextRow = this.tableData[rowIndex + 1]; //下一行数据
        // 当上一行的数据等于当前行数据时,当前行单元格隐藏
        if (prevRow && prevRow[column.property] === cellValue) {
          return { rowspan: 0, colspan: 0 };
        } else {
          // 反之,则循环判断若下一行数据等于当前行数据,则当前行开始进行合并单元格
          let countRowspan = 1; //用于合并计数多少单元格
          while (nextRow && nextRow[column.property] === cellValue) {
            nextRow = this.tableData[++countRowspan + rowIndex];
          }
          if (countRowspan > 1) {
            return { rowspan: countRowspan, colspan: 1 };
          }
        }
      }
    },