Element-ui table动态合并单元格

2,901 阅读1分钟

效果如下: avatar

<el-table
    :data="shortcutsData"
    height="100%"
    size="small"
    border
    style="width: 100%"
    :span-method="InTable"
  >
    <el-table-column
      label="分组名称"
      width="100"
      align="center"
      prop="groupName">
    </el-table-column>
    <el-table-column
      prop="type"
      label="类型"
      align="center"
      width="100">
    </el-table-column>
    <el-table-column
      prop="fastCoding"
      label="快捷编码"
      align="center"
      width="70">
    </el-table-column>
    <el-table-column
      label="快捷语"
      width="350">
      <template slot-scope="scope">
        <img :src="scope.row.content" class="imgSize"/>
      </template>
    </el-table-column>
    <el-table-column
      prop="shortFastType"
      label="快捷语类型"
      align="center"
      width="120"
    >
    </el-table-column>
    <el-table-column
      prop="updateTime"
      label="更新时间"
      align="center"
      width="150">
    </el-table-column>
    <el-table-column
      align="center"
      label="操作"
    >
      <template slot-scope="scope">
        <el-button type="text" size="small" @click="editShortcut(scope.row)">编辑快捷语</el-button>
        <el-button type="text" size="small" @click="delData(scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  
  data(){
    return {
        shortcutsData:[],//列表
        spanArr:[],//记录每一行的合并数
        pos:''//记录索引
    }
  },
  mounted(){
    this.spanArr=[];//注意:有翻页操作时许手动置空否则会错乱
    this.getSpanArr(this.shortcutsData);
  },
  methods:{
     getSpanArr(data) {
        for (var i = 0; i < data.length; i++) {
            if (i === 0) {
              this.spanArr.push(1);
              this.pos = 0;
            } else {
              // 判断当前元素与上一个元素是否相同
              if (data[i].groupId == data[i - 1].groupId) {
                this.spanArr[this.pos] += 1;
                this.spanArr.push(0);
              } else {
                this.spanArr.push(1);
                this.pos = i;
              }
            }
        }
    },
    InTable({ row, column, rowIndex, columnIndex }){
      if (columnIndex === 0) {
        const _row = this.spanArr[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col
        }
      };
    }
  }