el-table合并数据相同的单元格

178 阅读1分钟

el-table通用合并数据相同单元格方法


<script>
export default {
  data() {
    return {
      dialogVisible: false,//弹窗展示
      tableData: [
        {type: '1', rank: '100名以下', rate: '0.85', isCheck: true},
        {type: '1', rank: '101-300', rate: '0.95', isCheck: false},
        {type: '1', rank: '301-500', rate: '0.95', isCheck: false},
        {type: '2', rank: '100名以下', rate: '0.85', isCheck: false},
        {type: '2', rank: '101-300', rate: '0.95', isCheck: false},
        {type: '2', rank: '301-500', rate: '0.95', isCheck: false},
        {type: '3', rank: '100名以下', rate: '0.85', isCheck: false},
        {type: '3', rank: '101-300', rate: '0.95', isCheck: false},
        {type: '3', rank: '301-500', rate: '0.95', isCheck: false},
        {type: '4', rank: 'AA级', rate: '0.9', isCheck: false},
        {type: '4', rank: 'A级', rate: '0.95', isCheck: false},
      ],
    }
  },
  methods: {
    // 单元格合并方法
    spanMethod({row, column, rowIndex, columnIndex}) {
      //定义需要合并的列字段,有哪些列需要合并,就自定义添加字段即可
      const fields = ['type']
      // 当前行的数据
      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}
          }
        }
      }
    }
  }
}
</script>
摘自:https://devpress.csdn.net/chengdu/64e5f1a92ea0282871eaa745.html