Skip to content

Instantly share code, notes, and snippets.

@WangNingning1994
Created January 11, 2023 05:42
Show Gist options
  • Save WangNingning1994/72ca96cbe2b8faefa5d23522e209cbbf to your computer and use it in GitHub Desktop.
Save WangNingning1994/72ca96cbe2b8faefa5d23522e209cbbf to your computer and use it in GitHub Desktop.
Element UI table 合并单元格
<template>
<el-table
:data="tableData"
style="width: 100%"
:span-method="arraySpanMethod"
>
<el-table-column
prop="one"
label="一级分类"
width="180">
</el-table-column>
<el-table-column
prop="two"
label="二级分类"
width="180">
</el-table-column>
<el-table-column
prop="cpe023"
label="体征监测项">
</el-table-column>
</el-table>
</template>
<script>
export default {
props: {
msg: String,
},
name: 'HelloWorld',
created() {
let twoDimensionArr = this.mapTableDataToTwoDimensionArr(this.tableData);
let _twoDimensionArr = twoDimensionArr.map(item => this.calculateRowSpan(item));
this.spansArr = _twoDimensionArr;
},
methods: {
// 将表格数据转换成二维数组,数组的每一项是一个数组(一列)
mapTableDataToTwoDimensionArr(tableData) {
// 得到所有属性名,将返回['id', 'one', 'two', ... ];
const keys = Object.keys(tableData[0]);
let arr = keys.map(key => tableData.map(tableDataItem => tableDataItem[key]));
return arr; // [ [1,2,3], [213123, 213123, 13213, 13213]... ]
},
// 针对单列,计算各项的 rowspan
calculateRowSpan(columnDataArr) {
let currentIndex = 0; // 当前数组项下标
let firstSameValItemIndex = 0; // 和当前数组项值相同的数组项的第一个的下标
let lastSameValItemIndex = 0; // 和当前数组项值相同的数组项的最后一个的下标
// 先将每一项包装成对象, 默认rowspan为1,colspan所有都一样不会变,为1
columnDataArr = columnDataArr.map(val => ({ val, span: [1, 1] }));
// 遍历数组
columnDataArr.forEach((item, index) => {
currentIndex = index;
// 值相同的区间,直接跳出
if ((firstSameValItemIndex < currentIndex) && (currentIndex <= lastSameValItemIndex)) {
item.span = [0, 0];
return;
}
lastSameValItemIndex = currentIndex; // 先假设没有相同项
// 查找是否有和自己相同值的项目
let sameValItemLength = columnDataArr.filter(_item => _item.val === item.val).length;
if (sameValItemLength > 1) {
// debugger
firstSameValItemIndex = currentIndex;
lastSameValItemIndex = currentIndex + sameValItemLength - 1;
item.span = [sameValItemLength, 1] // 表示这个值将会横跨多行
}
});
return columnDataArr;
},
arraySpanMethod({ row, column, rowIndex, columnIndex }) {
return this.spansArr[columnIndex][rowIndex].span;
},
},
data() {
return {
spansArr: null,
tableData: [
{
// id : 1,
"one": "213123",
"two": "ces3",
"cpe023": "ces3",
},
{
// id : 2,
"one": "213123",
"two": "ces2",
"cpe023": "ces2",
},
{
// id : 3,
"one": "13213",
"two": "ces1",
"cpe023": "ces1",
},
{
// id : 4,
"one": "13213",
"two": "ces1",
"cpe023": "ces4",
},
{
// id : 4,
"one": "xxx",
"two": "test",
"cpe023": "test3",
}
]
}
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment