利用表格:span-method="" 方法实现合并单元格
合并前
合并后
重点代码generateIndexGroups ,找到合并的单元格的index号
代码实现如下
<template><h2>实现表格的合并</h2><div><!-- :span-method="arraySpanMethod" --><el-button type="primary" @click="testf">合并 </el-button><el-table:data="tableData"border:span-method="arraySpanMethod"style="width: 100%"@cell-click="cellClick"><el-table-columnalign="center"v-for="(item, index) in tabHeader":key="index":prop="item.prop":label="item.label":width="item.width"></el-table-column></el-table></div>
</template><script setup>
import { onMounted, reactive, ref } from "vue";
const tabHeader = [{ prop: "dept", label: "部门", width: 180 },{ prop: "name", label: "姓名" },{ prop: "area", label: "所属地" },
];const tableData = reactive([{dept: "部门1",name: "李1",area: "1",},{dept: "部门1",name: "李2",area: "1",},{dept: "部门1",name: "李3",area: "3",},{dept: "部门1",name: "李4",area: "2",},{dept: "部门2",name: "李1",area: "5",},{dept: "部门2",name: "李想3",area: "5",},{dept: "部门3",name: "李想33",area: "7",},
]);let mindexGroups = reactive([]);
let mnameGroups = reactive([]);
const merge = ref(false)onMounted(() => {mindexGroups = generateIndexGroups(tableData, ["dept"]);mnameGroups = generateIndexGroups(tableData, ["dept", "area"]);
});
function testf() {console.log(mindexGroups);merge.value = !merge.value;
}function arraySpanMethod({ row, column, rowIndex, columnIndex }) {if (merge.value != true){return;}//第0列if (columnIndex == 0) {for (let i = 0; i < mindexGroups.length; ++i) {if (rowIndex == mindexGroups[i].start) {return [mindexGroups[i].end - mindexGroups[i].start + 1, 1];}}return [0, 0];}//第2列if (columnIndex == 2) {for (let i = 0; i < mnameGroups.length; ++i) {if (rowIndex == mnameGroups[i].start) {return [mnameGroups[i].end - mnameGroups[i].start + 1, 1];}}return [0, 0];}
}function generateIndexGroups(data, field) {let tmp = data.map((i) => {let rstr = "";for (let j = 0; j < field.length; ++j) {rstr += "+" + i[field[j]];}console.log(i, rstr);return rstr;}); //排序return findIndexs(tmp);
}function findIndexs(array) {/* @params:数组return:一个包含重复序列,开始索引和结束索引的数组如:[{start:0;end:2},{start:3;end:5}]*/let current = array[0];let result = []; //返回结果let startIndex = 0;for (let i = 1; i < array.length; i++) {if (array[i] != current) {//if (startIndex == i -1) continue;result.push({ start: startIndex, end: i - 1 });current = array[i];startIndex = i;}}result.push({ start: startIndex, end: array.length - 1 });return result;
}
</script><style lang="scss" scoped></style>
参考:element-ui 合并行单元格,列-CSDN博客
element-ui 合并表格行_elementui表格合并行_nuise_的博客-CSDN博客