Vue + Element-ui 实现table表格 数据相同项合并
通过给table传入span-method方法可以实现合并行或列,方法的参数是一个对象
data() {
return {
tableArr: [], //定义空数组,作为临时存储每一行已处理的数据
pos:0, //
}
}
:span-method="SpanMethod" //Element-ui table表格的属性 ,例: <el-table :span-method="SpanMethod" ></el-table>
//获取数据,并对数据进行处理
for (var i = 0; i < data.length; i++) {
if (i === 0) {
this.tableArr.push(1);
this.pos = 0;
} else {
// 判断当前元素与上一个元素是否相同
if (data[i].DEPT_NAME === data[i - 1].DEPT_NAME) {
this.tableArr[this.pos] += 1;
//判断当前行与上一行内容相同时 返回0 ,0 意味消除 , 即不显示
this.tableArr.push(0);
} else {
this.tableArr.push(1);
this.pos = i;
}
}
}
实现合并相同项,
objectSpanMethod({ row, column, rowIndex, columnIndex }) {
if (columnIndex === 0) { //第一列
const _row = this.tableArr[rowIndex];
const _col = _row > 0 ? 1 : 0;
// console.log(`rowspan:${_row} colspan:${_col}`);
return {
// [0,0] 表示这一行不显示, [2,1]表示行的合并数
rowspan: _row,
colspan: _col,
};
}
},
当需要合并的列数不止第一列时
我这里只能分开写,写在一起的想法也尝试过
data() {
return {
//用了两个临时数组
tableArr: [], //定义空数组,作为临时存储每一行已处理的数据
spanArr:[],
pos:0, //
}
}
MergerTable(data) {
for (var i = 0; i < data.length; i++) {
if (i === 0) {
this.spanArr.push(1);
this.pos = 0;
} else {
// 判断当前元素与上一个元素是否相同
if (data[i].BU_NAME === data[i - 1].BU_NAME) {
this.spanArr[this.pos] += 1;
this.spanArr.push(0);
} else {
this.spanArr.push(1);
this.pos = i;
}
}
}
for (var i = 0; i < data.length; i++) {
if (i === 0) {
this.spanArr.push(1);
this.pos = 0;
} else {
// 判断当前元素与上一个元素是否相同
if (data[i].DEPT_NAME === data[i - 1].DEPT_NAME) {
this.spanArr[this.pos] += 1;
this.spanArr.push(0);
} else {
this.spanArr.push(1);
this.pos = i;
}
}
}
},
columnIndex 为你需要合并的那一列, 而我只需一,二列,按需使用
objectSpanMethod({ row, column, rowIndex, columnIndex }) {
if (columnIndex === 0) { //第一列
const _row = this.tableArr[rowIndex];
const _col = _row > 0 ? 1 : 0;
// console.log(`rowspan:${_row} colspan:${_col}`);
return {
// [0,0] 表示这一行不显示, [2,1]表示行的合并数
rowspan: _row,
colspan: _col,
};
}
if (columnIndex === 1) { //第二列
const _row = this.spanArr[rowIndex];
const _col = _row > 0 ? 1 : 0;
// console.log(`rowspan:${_row} colspan:${_col}`);
return {
// [0,0] 表示这一行不显示, [2,1]表示行的合并数
rowspan: _row,
colspan: _col,
};
}
},
代码有点冗余,但我还没有更好的解决办法
如有更好,也可让我也学习学习呀。