element ui中的table表格数据是动态生成的,如果要求我们对单元格进行合并,这个时候需要借助一个api,:span-method="arraySpanMethod",arraySpanMethod为我们自己编写的合并单元格的方法。
先在data中定义数据,合并几列就定义几个数组和索引
data() {
return {
tableData: [],//表格数据
batchNoInArr:[],//合并入库编号
batchNoInIndex:0,//合并入库编号索引
supplierNameArr:[],//合并供应商
supplierNameIndex:0,//合并供应商索引
}
}
定义合并的函数,并编写代码,merge方法中的data是table的数据源,逻辑是以第一行为基准一层层对比
// 初始化合并行数组
mergeInit() {
this.batchNoInArr = []; //合并入库编号
this.batchNoInIndex = 0;//合并入库编号索引
this.supplierNameArr = []; //合并供应商
this.supplierNameIndex = 0;//合并供应商索引
},
// 合并表格
merge() {
this.mergeInit();
let data = this.tableData;
if (data.length > 0) {
for (var i = 0; i < data.length; i++) {
if (i === 0) {
//第一行必须存在,以第一行为基准
this.batchNoInArr.push(1); //合并入库编号
this.batchNoInIndex = 0;
this.supplierNameArr.push(1);//合并供应商
this.supplierNameIndex = 0;
} else {
// 判断当前元素与上一元素是否相同
// 合并入库编号
if (data[i].batchNoIn == data[i - 1].batchNoIn) {
this.batchNoInArr[this.batchNoInIndex] += 1;
this.batchNoInArr.push(0);
} else {
this.batchNoInArr.push(1);
this.batchNoInIndex = i;
}
//合并供应商,注意if条件以前面列为基准
if (data[i].batchNoIn == data[i - 1].batchNoIn && data[i].supplierName == data[i - 1].supplierName) {
this.supplierNameArr[this.supplierNameIndex] += 1;
this.supplierNameArr.push(0);
} else {
this.supplierNameArr.push(1);
this.supplierNameIndex = i;
}
}
}
}
},
//合并方法
objectSpanMethod({ row, column, rowIndex, columnIndex }) {
if (columnIndex === 0) {
//第一列 入库编号
const row1 = this.batchNoInArr[rowIndex];
const col1 = row1 > 0 ? 1 : 0;
return {
rowspan: row1,
colspan: col1
};
}else if (columnIndex === 1) {
// 第二列 供应商
const row2 = this.supplierNameArr[rowIndex];
const col2 = row2 > 0 ? 1 : 0;
return {
rowspan: row2,
colspan: col2,
};
}
},
<el-table :data="tableData" :span-method="objectSpanMethod"></el-table>