先上效果图
一、在中加上span-method方法合并行
// 合并行
arraySpanMethod({ row, column, rowIndex, columnIndex }) {
this.setrowspans();
//第一列和第五列的字段相同时合并
if (columnIndex === 0 || columnIndex === 4) {
return {
rowspan: row.rowspan,
colspan: 1,
};
}
},
// 设置合并行
setrowspans() {
// 先给所有的数据都加一个v.rowspan = 1
this.materialsData.forEach((v) => {
v.rowspan = 1;
});
// 双层循环
for (let i = 0; i < this.materialsData.length; i++) {
// 内层循环,上面已经给所有的行都加了v.rowspan = 1
// 这里进行判断
// 如果当前行的id和下一行的id相等
// 就把当前v.rowspan + 1
// 下一行的v.rowspan - 1
for (let j = i + 1; j < this.materialsData.length; j++) {
if (this.materialsData[i].cItems === this.materialsData[j].cItems) {
this.materialsData[i].rowspan++;
this.materialsData[j].rowspan--;
}
}
// 这里跳过已经重复的数据
i = i + this.materialsData[i].rowspan - 1;
}
},
二、点击新增按钮,数据穿梭
难点是合并行的数据带到另一个表格中,点击新增按钮,插槽scope.row保存的只有第一行的值,要把后几行的数据一并带过去就需要获取合并行的rowspan,也需要获取选中第一行的index。
核心代码:
vue:
<el-table-column
:label="操作"
width="75"
>
<template slot-scope="scope">
<el-button
type="primary"
size="mini"
@click="addBtn(scope.row, scope.$index)"
style="font-size: 6px"
>新增</el-button
>
</template>
</el-table-column>
js:
addBtn(row, index){
for (let i = index; i < index + row.rowspan; i++) {
let obj = {
cItems: row.cItems,
cCode: this.materialsData[i].cCode,
};
this.feedInForData.push(obj);
}
}
三、移除和上下移动操作
这里的难点是上下移操作的插入位置和插入项。
上移操作需要计算上一条合并行数据的行数,
下移操作需要计算下一条合并行数据的行数。
上移时选中数据的index往前遍历数组,下移时选中数据的index往后遍历数组,判断相邻两项的第一列字段是否相同,同就+1,不同就跳出循环。这里一定要记得跳出,
vue:
<el-table-column
:label="操作"
width="110"
>
<template slot-scope="scopes">
<a
href="JavaScript:;"
@click="cRemove(scopes.row, scopes.$index)"
style="margin-right: 5px"
>移除</a
>
<a
href="JavaScript:;"
@click="onUpItem(scopes.row, scopes.$index)"
style="margin-right: 5px"
v-show="scopes.$index !== 0"
>上移</a
>
<a
href="JavaScript:;"
@click="onDownItem(scopes.row, scopes.$index)"
v-show="
scopes.$index !==
feedInForData.length - scopes.row.rowspan
"
>下移</a
>
</template>
</el-table-column>
//移除操作
cRemove(row, index) {
this.feedInForData.splice(index, row.rowspan);
},
//上移操作
onUpItem(row, index) {
let preRowSpan = 1; //上一条数据的合并行数
for (let j = index - 1; j > 0; j--) {
if (this.feedInForData[j].cItems == this.feedInForData[j - 1].cItems) {
preRowSpan += 1;
} else {
break;
}
}
for (let i = 0; i < row.rowspan; i++) {
//插入:3个参数(插入位置,0,插入项)
this.feedInForData.splice(
index + i - preRowSpan,
0,
this.feedInForData[index + 2 * i]
);
}
//删除:两个参数(要删除第一项的位置,要删除的项数)
this.feedInForData.splice(index + row.rowspan, row.rowspan);
},
//下移操作
onDownItem(row, index) {
let nextRowSpan = 1; //下一条数据的合并行数
for (
let j = index + row.rowspan;
j < this.feedInForData.length - 1;
j++
) {
if (this.feedInForData[j].cItems == this.feedInForData[j + 1].cItems) {
nextRowSpan += 1;
} else {
break;
}
}
for (let i = 0; i < row.rowspan; i++) {
//插入:3个参数(插入位置,0,插入项)
this.feedInForData.splice(
index + i + nextRowSpan + row.rowspan,
0,
this.feedInForData[index + i]
);
}
//删除:两个参数(要删除第一项的位置,要删除的项数)
this.feedInForData.splice(index, row.rowspan);
},