vue中 表頭th 合併單元格,且表格列數不定的動態渲染方法
阿新 • • 發佈:2018-11-03
吐槽
今天,在vue中遇到 複雜表格的渲染 ,需要合併表頭的單元格,且合併單元格的那列還是動態資料,也就是說你不知道會有多少組要合併起來,哎,我也有點說不清楚,廢話不多說了,看程式碼把:
程式碼示例
data資料是後端介面返回的,其中的資料格式是這樣的:
[ { "studentId": "ff808081651e03d4016530b937f50a33", "studentName": "傅xx", "studentCode": "91scdsc109", "sex": { "value": "MALE", "name": "男" }, "termName": "2018秋", "examDates": [ "10月", "9月28日" ], "map": { "9月28日": [ { "courseName": "聽力", "scorel": 6.0 }, { "courseName": "閱讀", "score": 7.0 }, { "courseName": "寫作", "scorel": 5.5 } ] }, "courseNames": [ "聽力", "閱讀", "寫作", "口語", "總分" ] }, { "studentId": "ff8080816483a43d01648723c52801bc", "studentName": "陳xx", "studentCode": "91edfedf3", "sex": { "value": "FEMALE", "name": "女" }, "termName": "2018秋", "examDates": [ "10月", "9月28日" ], "map": { "9月28日": [ { "courseName": "聽力", "score": 5.5, "order": 0 }, { "courseName": "閱讀", "score": 6.0, "order": 1 }, { "courseName": "寫作", "score": 5.5, "order": 2 }, { "courseName": "口語", "scoreFinal": 5.5, "order": 3 } ] }, "courseNames": [ "聽力", "閱讀", "寫作", "口語", "總分" ] } ]
獲取到以上資料後,對資料稍微處理下:
<table class="table"> <thead> <tr> <th rowspan="2">序號</th> <th rowspan="2">姓名</th> <th rowspan="2">學號</th> <th rowspan="2">性別</th> <th rowspan="2">學期</th> <th colspan="5" v-for="(it,i) in examDates" :key="i">{{it}}</th> </tr> <tr> <template v-for="itd in examDates"> <th v-for="(itc,j) in courseNames" :key="itd+j">{{itc}}</th> </template> </tr> </thead> <tbody> <tr v-for="(item,index) in studentDataList" :key="index"> <td>{{index+1}}</td> <td>{{item.studentName}}</td> <td>{{item.studentCode}}</td> <td>{{item.sex.name}}</td> <td>{{item.termName}}</td> <template v-for="examDate in examDates"> <template v-for="(course,j) in courseNames"> <td :key="examDate+j"> {{initScoreFinal(examDate,course,item.map)}} </td> </template> </template> </tr> </tbody> </table> ---------------- 分割線 --------------------------------------- data () { return { studentDataList: [], examDates: [], courseNames: [] }, created () { this.getData () }, methods: { // getData () { this.$get( //該方法是封裝過的axios '/list.json', { ....//此處是引數,略 }, response => { this.examDates = response.data[0].examDates courseNames = response.data[0].courseNames this.studentDataList = response.data } ) }, initScoreFinal (examDate, course, map) { let scoreFinal = 0 console.log('map:' + map) for (var it in map) { map[it].forEach((item, index, array) => { if (it === examDate && item.courseName === course) { scoreFinal = item.scoreFinal } }) } return scoreFinal } }
效果如圖:
再吐個槽
在網上搜了很多合併單元格的都是簡單的資料合併,也就是td
合併,我們這邊的專案需要的這個表格比較變態,按日期分組的去五門課程,且日期數目不定,又可能多個日期,這就很頭疼了,總之長知識了,記錄下來。