Element table表格根据某几个字段进行合并例子
比如 十条数据 根据 a b c d四个字段 如果相邻的对象这四个值相同就进行合并
使用:span-method="objectSpanMethod"
<el-table
:data="data"
:highlight-current-row="true"
:span-method="objectSpanMethod"
>
<el-table-column width="50" label="序号">
<template slot-scope="scope">{{
(scope.row.group) + 1
}}</template>
</el-table-column>
<el-table-column label="a" prop="a"/>
<el-table-column label="b" prop="b"/>
<el-table-column label="c" prop="c"/>
<el-table-column label="d" prop="d"/>
<el-table-column label="e" prop="e" />
<el-table-column label="f" prop="f" />
<el-table-column label="g" prop="g" />
</el-table>
data(){
return{
spanArr: [],
data: [
{ a: 1, b: 1, c: 1, d: 1, e: 666, f: 777 },
{ a: 1, b: 1, c: 1, d: 1, e: "e", f: "f" },
{ a: 1, b: 1, c: 1, d: 1, e: "x", f: "y" },
{ a: 1, b: 1, c: 1, d: 1, e: "z", f: "adsf" },
{ a: 2, b: 1, c: 1, d: 1, e: "z11", f: "adsf" }
],
}
},
methods:{
objectSpanMethod({ row, column, rowIndex, columnIndex }) {
// 第5 6 7列不合并 也就是 e f g列不合并 columnindex从0开始
if (columnIndex !== 5 && columnIndex !== 6 && columnIndex !== 7) {
const _row = this.spanArr[rowIndex];
const _col = _row > 0 ? 1 : 0;
return {
rowspan: _row,
colspan: _col
};
}
},
handleData() {
//sortByArr是排序方法 后面有讲
this.data.sort(sortByArr(["a", "b", "c", "d"], true));
let contactDot = 0;
this.spanArr = [];
this.data.forEach((item, index) => {
item.index = index;
if (index === 0) {
this.spanArr.push(1);
item.group = index; //先设置组号赋值为0 也就是序号
} else {
// a b c d四个字段相同进行合并
if (
item.a === this.data[index - 1].a &&
item.b === this.data[index - 1].b &&
item.c === this.data[index - 1].c &&
item.d === this.data[index - 1].d
) {
this.spanArr[contactDot] += 1;
this.spanArr.push(0);
item.group = this.data[index - 1].group; //如果一样 将组号改为和上一个数据相同
} else {
this.spanArr.push(1);
contactDot = index;
item.group = this.data[index - 1].group + 1; //如果不一样 将组号设置为上一个数据的组号加1
}
}
});
},
},
mounted(){
this.handleData()
}
注意: 如果想要合并的数据不在相邻位置 请先对数据进行按字段排序
/**数组根据数组对象中的某个属性值进行排序的方法
* 使用例子:newArray.sort(sortByArr(['number'],false)) //表示根据number属性降序排列;若第二个参数不传递,默认表示升序排序
* @param attr 排序的属性 ['name','sex'...],根据一个字段或者多个字段排序
* @param rev true表示升序排列,false降序排序
* */
export function sortByArr(arr, rev) {
if (rev == undefined) {
rev = 1;
} else {
rev = rev ? 1 : -1;
}
return function(a, b) {
for (var i = 0; i < arr.length; i++) {
let attr = arr[i];
if (a[attr] != b[attr]) {
if (a[attr] > b[attr]) {
return rev * 1;
} else {
return rev * -1;
}
}
}
};
}
多字段单独排序可参考http://t.csdn.cn/c7fhA