在项目开发过程中,会遇到合并表格
的情况,这里针对第一列的重复数据进行合并展示
页面代码
<el-table
:data="dataList"
:span-method="handleSpanMethod"
border
>
<el-table-column label="班级" align="center" prop="className" />
<el-table-column label="姓名" align="center" prop="name" />
<el-table-column label="年龄" align="center" prop="age" />
</el-table>
JS代码实现
data() {
return {
spanArr: [],
pos: 0,
dataList: [
{
className: '高一三班', name: '张三', age: 18 },
{
className: '高一三班', name: '张无忌', age: 19 },
{
className: '高一六班', name: '王五', age: 18 },
{
className: '高一七班', name: '赵六', age: 19 },
{
className: '高一八班', name: '杜画', age: 20 },
]
}
},
created() {
this.getSpanArr(this.dataList);
},
methods: {
getSpanArr(data) {
this.spanArr = [];
this.pos = 0;
data.map((item, index) => {
if (index == 0) {
this.spanArr.push(1);
this.pos = 0;
} else {
if (data[index].className === data[index - 1].className) {
this.spanArr[this.pos] += 1;
this.spanArr.push(0);
} else {
this.spanArr.push(1);
this.pos = index;
}
}
});
},
handleSpanMethod({
row, column, rowIndex, columnIndex }) {
if (columnIndex === 0) {
const _row = this.spanArr[rowIndex];
const _col = _row > 0 ? 1 : 0;
return {
rowspan: _row,
colspan: _col,
};
} else {
return false;
}
},
}