el-table 合并单元格 合并指定列一整列

2023-12-07  本文已影响0人  执着于98斤的it女
<template>
  <el-table :data="tableData" border :span-method="objectSpanMethod">
    <el-table-column prop="name" label="名称"></el-table-column>
    <el-table-column prop="age" label="年龄"></el-table-column>
    <el-table-column prop="gender" label="性别"></el-table-column>
  </el-table>
</template>

<script>
export default {
  data() {
    return {
      tableData: [
        { name: '张三', age: 18, gender: '男' },
        { name: '李四', age: 20, gender: '男' },
        { name: '王五', age: 22, gender: '女' },
        { name: '赵六', age: 25, gender: '男' },
      ],
    };
  },
  methods: {
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 1) {
        // 判断是否需要合并单元格
        if (rowIndex === 0 || row.name !== this.tableData[rowIndex - 1].name) {
          const rowspan = this.getRowspan({ row, column, rowIndex, columnIndex });
          return { rowspan, colspan: 1 };
        } else {
          return { rowspan: 0, colspan: 0 };
        }
      }
    },
    getRowspan({ row, column, rowIndex, columnIndex }) {
      let rowspan = 1;
      for (let i = rowIndex + 1; i < this.tableData.length; i++) {
        if (this.tableData[i].name === row.name) {
          rowspan++;
        } else {
          break;
        }
      }
      return rowspan;
    },
  },
};
</script>
上一篇 下一篇

猜你喜欢

热点阅读