1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
| <template> <div class="table"> <el-table :data="tableData" :span-method="objectSpanMethod" border style="width: 100%"> <el-table-column label="时间" prop="time" /> <el-table-column label="年级" prop="grade" /> <el-table-column label="姓名" prop="name" /> <el-table-column label="科目" prop="subjects" /> <el-table-column label="成绩" prop="score" /> </el-table> </div> </template>
<script> export default { name: 'Table', data() { return { tableData: [ { time: '2024-08-10', grade: '五年级二班', name: '张三', subjects: '语文', score: 80 }, { time: '2024-08-10', grade: '五年级二班', name: '张三', subjects: '数学', score: 80 }, { time: '2024-08-10', grade: '五年级一班', name: '李四', subjects: '语文', score: 70 }, { time: '2024-08-10', grade: '五年级一班', name: '李四', subjects: '数学', score: 80 }, { time: '2024-08-11', grade: '五年级三班', name: '大飞', subjects: '语文', score: 60 }, { time: '2024-08-11', grade: '五年级三班', name: '大飞', subjects: '数学', score: 60 }, ], mergeObj: {}, // 用来记录需要合并行的下标 mergeArr: ['time', 'grade', 'name', 'subjects', 'score'], // 表格中的列名 // mergeArr: ['time', 'subjects'], // 表格中的列名 }; }, methods: { getSpanArr(data) { this.mergeArr.forEach((key, index1) => { let count = 0; // 用来记录需要合并行的起始位置 this.mergeObj[key] = []; // 记录每一列的合并信息 data.forEach((item, index) => { // index == 0表示数据为第一行,直接 push 一个 1 if(index === 0) { this.mergeObj[key].push(1); } else { // 判断当前行是否与上一行其值相等 如果相等 在 count 记录的位置其值 +1 表示当前行需要合并 并push 一个 0 作为占位 if(item[key] === data[index - 1][key]) { this.mergeObj[key][count] += 1; this.mergeObj[key].push(0); } else { // 如果当前行和上一行其值不相等 count = index; // 记录当前位置 this.mergeObj[key].push(1); // 重新push 一个 1 } } }) }) }, // 默认接受四个值 { 当前行的值, 当前列的值, 行的下标, 列的下标 } objectSpanMethod({ row, column, rowIndex, columnIndex }) { // 判断列的属性 if(this.mergeArr.indexOf(column.property) !== -1) { // 判断其值是不是为0 if(this.mergeObj[column.property][rowIndex]) { return [this.mergeObj[column.property][rowIndex], 1] } else { // 如果为0则为需要合并的行 return [0, 0]; } } } }, mounted() { this.getSpanArr(this.tableData); } }; </script>
<style scoped lang="scss"> .table { height: 100vh; width: 100%; padding: 40px; box-sizing: border-box;
} </style>
|