新建tableMerge.js文件
/**
* 合并表格单元格类
* 提示:
* 1.如果table表格需要加合并后的序号,只需要给el-table-column标签加 prop="group" 即可
* 使用方式:
* 1.在script中引入tableMerge.js文件 import tableMerge from "@/utils/tableMerge.js";
* 2.在data()函数中定义变量newTableMerge=null
* 3.在created生命周期中实例化tableMerge类:
* this.newTableMerge = new tableMerge(this.needMergeArr);
* 提示:
* this.needMergeArr为要合并的单元格属性数组,比如:this.needMergeArr=["indicatorName", "tz", "jjcl"]
* 4.在获取完tableData列表数据的下一行执行合并数据函数this.newTableMerge.tableDataMerge(this.tableData)
* 5.在el-table标签中添加函数事件:span-method="(params) => newTableMerge.objectSpanMethod(params)"
*/
export default class tableMerge {
constructor(needMergeArr) {
// tableData数据
this.tableData = []
// needMergeArr 需要合并列的属性array形式
this.needMergeArr = needMergeArr
console.log(this.needMergeArr)
this.spanArr = []
}
// tableData的数据合并
tableDataMerge(tableData) {
this.tableData = tableData
let contactDot = 0;
this.spanArr = [];
let n = "";
this.tableData.forEach((item, index) => {
item.index = index;
if (index === 0) {
this.spanArr.push(1);
item.group = 1; //先设置组号赋值为0 也就是序号
} else {
for (let i = 0; i < this.needMergeArr.length; i++) {
let reg = /(=== | &&)/g;
let nArr = n.replace(reg, " ");
if (!nArr.includes(`item["${this.needMergeArr[i]}"]`)) {
n += `item["${this.needMergeArr[i]}"] ===
_this.tableData[index - 1]["${this.needMergeArr[i]}"]
&& `;
}
}
let str = n.replace(/( && ){1}$/g, "");
// n='贷款规模 === 贷款规模 && 年初资产总额 === 年初资产总额'
if (eval(str)) {
this.spanArr[contactDot] += 1;
this.spanArr.push(0);
item.group = this.tableData[index - 1].group; //如果一样 将组号改为和上一个数据相同
} else {
this.spanArr.push(1);
contactDot = index;
item.group = this.tableData[index - 1].group + 1; //如果不一样 将组号设置为上一个数据的组号加1
}
}
})
}
// table的:span-method函数
objectSpanMethod({ row, column, rowIndex, columnIndex }) {
// group为合并序号
let n = 'column.property === "group" ||'
for (let i = 0; i < this.needMergeArr.length; i++) {
let reg = /(=== | \|\|)/g;
let nArr = n.replace(reg, " ");
if (!nArr.includes(`item["${this.needMergeArr[i]}"]`)) {
n += `column.property === "${this.needMergeArr[i]}"
|| `;
}
}
let reg = /( \|\| ){1}$/g
let str = n.replace(reg, "");
if (
eval(str)
) {
const _row = this.spanArr[rowIndex];
const _col = _row > 0 ? 1 : 0;
return {
rowspan: _row,
colspan: _col,
};
}
}
}