el-table 怎么把表格相同的数据 合并为一行

1. 如题 近期遇到一个单元格需要合并的需求,因为使用的 饿了么ui里的 el-table,就看了一下它官网给的例子,可以使用属性 :span-method  来实现,但是 给的例子是 直接固定死 合并第几行了,实际项目中,我们肯定不能这么干,数据不确定的情况下,我们也不知道合并到第几行,刚好可以用他的值来判断,如果是相同的值,就给他把这一行合并了,不就行了。。

2. 示例:假如  我们要把名称这一列里面的值相同的合并到一起,先在表格上添加:span-method属性,然后写函数就行。是名称列,其它列不需要管。

3.前提是 已经从后台拿到数据了,tableData 已经有数据了。

  <el-table   :data="tableData"  :height="tableHeight"   size="mini" 
      :span-method="genderSpanCity">
     <el-table-column  prop="categoryName" label="名称" fixed align="left" width="150"  
      show-overflow-tooltip> </el-table-column>
     <el-table-column  prop="name" label="地市" fixed align="left" width="150"  show- 
      overflow-tooltip> </el-table-column>
     <el-table-column label="历史数据" align="center"  >
         <el-table-column     
              v-for="(item, index) in tableHeader"
                  :key="index"
                  :label="item" 
                   width="150"
                  align="center">
             <template slot-scope="scope" v-if="scope.row.unit">
                 <el-input v-model="scope.row.vals[index].val"   size="mini" 
                   :readonly="scope.row.vals[index].editType === 1"                                                              :class="scope.row.vals[index].editType===1?'input1':scope.row.vals[index].editType===2?'class1':'class2'"                                    :value="formatValue(scope.row.vals[index].val,scope.row)"    @focus="updateValue(scope.row.vals[index], 'val')" style="width: 100%;">
      <template slot="append" v-if="scope.row.unit=='%'||scope.row.unit=='%'"> %            
      </template>    
     </el-input>
           </template>
     </el-table-column>
  </el-table-column>  
</el-table> 
     genderSpanCity({ row, column, rowIndex, columnIndex }) {
         if (columnIndex === 0) {
            // 获取当前单元格的值
             const currentValue = row[column.property];
             // 获取上一行相同列的值
              const preRow = this.tableData[rowIndex - 1];
              const preValue = preRow ? preRow[column.property] : null;
              // 如果当前值和上一行的值相同,则将当前单元格隐藏
                if (currentValue === preValue) {
                      return { rowspan: 0, colspan: 0 };
                    } else {
                      // 否则计算当前单元格应该跨越多少行
                      let rowspan = 1;
                      for (let i = rowIndex + 1; i < this.tableData.length; i++) {
                        const nextRow = this.tableData[i];
                        const nextValue = nextRow[column.property];
                        if (nextValue === currentValue) {
                          rowspan++;
                        } else {
                          break;
                        }
                      }
                      return { rowspan, colspan: 1 };
                    }
                  }   
                },

科普:propertyel-table-column 组件的一个属性,用于指定该列要渲染的数据字段名。

最终效果:

猜你喜欢

转载自blog.csdn.net/qq_42174597/article/details/130602030