<el-table>
把表格内同一列相同的数据合并为一行
具体效果如下图:
参考代码(可直接运行):
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width,initial-scale=1.0"/>
<script src="https://unpkg.com/vue@3"></script>
<link rel="stylesheet" href="https://unpkg.com/element-plus/dist/index.css">
<script src="https://unpkg.com/element-plus"></script>
<title>合并行或列</title>
</head>
<body>
<div id="view_table_merge_columns" class="common-layout">
<el-table
:data="tableData"
:span-method="objectSpanMethod"
border
stripe
style="width: 100%"
:header-cell-style="{ textAlign: 'center', 'background-color': '#F5F7FA', }"
:cell-style="{ textAlign: 'center' }"
>
<el-table-column prop="id" label="编号"></el-table-column>
<el-table-column prop="first" label="一级标题"></el-table-column>
<el-table-column prop="second" label="二级标题"></el-table-column>
<el-table-column prop="third" label="三级标题"></el-table-column>
<el-table-column prop="outcome" label="结果"></el-table-column>
</el-table>
</div>
<script>
const App = {
data() {
return {
needToMergeColumns: ['first', 'second', 'third'],
tableData: [
{
id: '101',
first: '第一单元',
second: '第一课',
third: '问题一',
outcome: 10,
},
{
id: '102',
first: '第一单元',
second: '第二课',
third: '问题一',
outcome: 10,
},
{
id: '103',
first: '第一单元',
second: '第二课',
third: '问题二',
outcome: 10,
}, {
id: '104',
first: '第二单元',
second: '第一课',
third: '问题一',
outcome: 10,
},
{
id: '105',
first: '第二单元',
second: '第一课',
third: '问题二',
outcome: 9,
},
{
id: '106',
first: '第三单元',
second: '第一课',
third: '问题一',
outcome: 5,
},
],
};
},
methods: {
objectSpanMethod({row, column, rowIndex, columnIndex}) {
console.log(row);
console.log(column);
console.log(rowIndex, columnIndex);
if (this.needToMergeColumns.indexOf(column.property) !== -1) {
const currentValue = row[column.property];
const preRow = this.tableData[rowIndex - 1];
const preValue = preRow ? preRow[column.property] : null;
if (currentValue === preValue) {
return {'rowspan': 0, 'colspan': 0};
} else {
let rowspan = 1;
for (let i = rowIndex + 1; i < this.tableData.length; i++) {
const nextRow = this.tableData[i];
const nextValue = nextRow[column.property];
if (nextValue === currentValue) {
rowspan++;
} else {
break;
}
}
return {'rowspan': rowspan, 'colspan': 1};
}
}
}
}
};
const app = Vue.createApp(App);
app.use(ElementPlus);
app.mount("#view_table_merge_columns");
</script>
</body>
</html>