本文主要是介绍<el-table> 把表格内同一列相同的数据合并为一行,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
<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><!-- import CSS --><link rel="stylesheet" href="https://unpkg.com/element-plus/dist/index.css"><!-- import JavaScript --><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"borderstripestyle="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: {// 同一列内合并值相同行 (当前行 row、当前列 column、当前行号 rowIndex、当前列号 columnIndex 四个属性)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>
这篇关于<el-table> 把表格内同一列相同的数据合并为一行的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!