ElementUI中合并表格列
在elementui组件库里的合并比较各行和列方法比较单一:
// 两列合为一列
arraySpanMethod({ row, column, rowIndex, columnIndex }) {
if (rowIndex % 2 === 0) {
if (columnIndex === 0) {
return [1, 2];
} else if (columnIndex === 1) {
return [0, 0];
}
}
},
// 两行合为一行
objectSpanMethod({ row, column, rowIndex, columnIndex }) {
if (columnIndex === 0) {
if (rowIndex % 2 === 0) {
return {
rowspan: 2,
colspan: 1
};
} else {
return {
rowspan: 0,
colspan: 0
};
}
}
现在如果想把第一列中内容相同的行合并为一行,该怎么写呢?
首先,data里定义两个属性
spanArr: [], // 用于存放需要合并的行的个数
spanIndex: 0, // 记录spanArr数组的下标
// 表格
<el-table
:data="nodesData"
:span-method="objectSpanMethod"
border
>
判断表格第一列中每行的数据是否相同,相同的话,合并
// 处理数据
getSpanArr(data) {
for (let i = 0; i < data.length; i++) {
if (i === 0) {
this.spanArr.push(1);
this.spanIndex = 0;
} else {
// 判断当前行与前一行内容是否相同
if (data[i].process === data[i - 1].process) {
this.spanArr[this.spanIndex] += 1; // 相同的话,当前下标所代表的值加一,例如:第一列的前三行可合并
this.spanArr.push(0);// 记录完毕后,再往数组里添加一个元素0,作为下一次合并的初始值
} else {
this.spanArr.push(1); // 否则,依旧是一行
this.spanIndex = i;
}
}
}
},
// 合并列
objectSpanMethod({ row, column, rowIndex, columnIndex }) {
if (columnIndex === 0) {
const _row = this.spanArr[rowIndex]; // 行数
const _col = _row > 0 ? 1 : 0; // 列数
return {
rowspan: _row,
colspan: _col
};
}
},
最后,在created()方法中调用getSpanArr()
created() {
this.getSpanArr(this.nodesData); // nodesData是表格中的数据
},
效果