背景
現(xiàn)實(shí)中會遇到很多需求,合并列,例如要顯示一個名學(xué)生的各門課程成績。

html實(shí)現(xiàn)
使用html實(shí)現(xiàn)是比較簡單的,利用table標(biāo)簽的rowspan屬性即可,代碼如下:
<table> <thead> <tr> <th>姓名</th> <th>課程數(shù)</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>數(shù)學(xué)</td> <td>90</td> </tr> <tr> <td>英語</td> <td>80</td> </tr> </tbody></table>
數(shù)據(jù)結(jié)構(gòu)
在實(shí)際工程中,表格數(shù)據(jù)一般來自后端,以json格式發(fā)送到前端后,學(xué)生和課程是一對多的關(guān)系,json格式數(shù)據(jù)結(jié)構(gòu)如下:
[ { name: '張三', courses: [ { name: '語文', score: '100' }, { name: '數(shù)學(xué)', score: '90' }, { name: '英語', score: '80' } ] }]Vue實(shí)現(xiàn)
我們對比表格結(jié)構(gòu)和json數(shù)據(jù)結(jié)構(gòu),分析出結(jié)論如下:
1.實(shí)際上每個課程對應(yīng)表格的一行
2.如果是第一列第二列(學(xué)生姓名、學(xué)生課程數(shù)),則應(yīng)設(shè)置其rowspan值為該學(xué)生擁有的課程數(shù)
3.如果是第一列第二列,則每個學(xué)生只需要輸出1次該列,因?yàn)樾枰磳W(xué)生合并列后展示。
分析完1-3條后,代碼實(shí)現(xiàn)也就簡單了:
<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>課程數(shù)</th> <th>課程名稱</th> <th>成績</th> </thead> <tbody> <template v-for="(item,index) in students"> <tr v-for="(m,i) in item.courses"> <!-- 第1列每個學(xué)生只需要展示1次 --> <td v-if="i==0" :rowspan="item.courses.length"> {{item.name}} </td> <!-- 第2列每個學(xué)生只需要展示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: '數(shù)學(xué)', score: '90' }, { name: '英語', score: '80' } ] }, { name: '李四', courses: [ { name: '語文', score: '100' }, { name: '數(shù)學(xué)', score: '90' } ] } ] } }); </script></body></html>效果:

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答