Vue实现数据表格合并列rowspan效果

Malak ·
更新时间:2024-09-21
· 511 次阅读

背景

现实中会遇到很多需求,合并列,例如要显示一个名学生的各门课程成绩。

html实现

使用html实现是比较简单的,利用table标签的rowspan属性即可,代码如下:

<table> <thead> <tr> <th>姓名</th> <th>课程数</th> <th>课程名称</th> <th>成绩</th> </tr> </thead> <tbody> <tr> <td rowspan="3"> 张三 </td> <td rowspan="3"> 3 </td> <td>语文</td> <td>100</td> </tr> <tr> <td>数学</td> <td>90</td> </tr> <tr> <td>英语</td> <td>80</td> </tr> </tbody> </table>

数据结构

在实际工程中,表格数据一般来自后端,以json格式发送到前端后,学生和课程是一对多的关系,json格式数据结构如下:

[ { name: '张三', courses: [ { name: '语文', score: '100' }, { name: '数学', score: '90' }, { name: '英语', score: '80' } ] } ]

Vue实现

我们对比表格结构和json数据结构,分析出结论如下:

1.实际上每个课程对应表格的一行
2.如果是第一列第二列(学生姓名、学生课程数),则应设置其rowspan值为该学生拥有的课程数
3.如果是第一列第二列,则每个学生只需要输出1次该列,因为需要按学生合并列后展示。

分析完1-3条后,代码实现也就简单了:

<html> <head> <style> th { border: 1px solid black; width: 100px; } td { border: 1px solid black; } </style> </head> <body> <div id="app"> <table> <thead> <th>姓名</th> <th>课程数</th> <th>课程名称</th> <th>成绩</th> </thead> <tbody> <template v-for="(item,index) in students"> <tr v-for="(m,i) in item.courses"> <!-- 第1列每个学生只需要展示1次 --> <td v-if="i==0" :rowspan="item.courses.length"> {{item.name}} </td> <!-- 第2列每个学生只需要展示1次 --> <td v-if="i==0" :rowspan="item.courses.length"> {{item.courses.length}} </td> <td>{{m.name}}</td> <td>{{m.score}}</td> </tr> </template> </tbody> </table> </div> <script src="https://cdn.bootcss.com/vue/2.6.10/vue.js"></script> <script> var vm = new Vue({ el: "#app", data: { students: [ { name: '张三', courses: [ { name: '语文', score: '100' }, { name: '数学', score: '90' }, { name: '英语', score: '80' } ] }, { name: '李四', courses: [ { name: '语文', score: '100' }, { name: '数学', score: '90' } ] } ] } }); </script> </body> </html>

效果:



VUE 表格 数据 rowspan 数据表

需要 登录 后方可回复, 如果你还没有账号请 注册新账号