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 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
| <template> <div> <h1>demo11</h1> <table class="table"> <thead> <tr> <th v-for="head in tableHead" :key="head">{{head}}</th> </tr> </thead> <tbody> <tr v-for="item in tableData" :key="item.key"> <td v-for="data in item.data" :key="data.value" :rowspan="data.rowspan" v-if="!data.hidden">{{data.value}} </td> </tr> </tbody> </table> </div> </template>
<script> export default { name: 'demo36', props: [], data() { return { tableHead: ['省份', '市', '区'], tableBody: [ ['四川', '成都市', '温江区'], ['四川', '宜宾市', '全部市区'], ['四川', '宜宾市', '全部市区2'], ['四川1', '宜宾市', '全部市区3'], ['四川2', '宜宾市', '全部市区4'], ['四川2', '宜宾市4', '全部市区4'], ], } }, methods: { handleTableData(tableBody, tableHead) {
function prevSame(result, i, j, startRowIndex) { while (j >= 1) { if (result[i][j - 1].value === result[startRowIndex][j - 1].value) { j--; } else { return false } } return true }
let result = tableBody.map(v => [...v.map(val => ({ value: val }))]); let startRowIndex = 0; for (let j = 0; j < tableHead.length; j++) { for (let i = 0; i < result.length; i++) { let rowSpanName = result[startRowIndex][j].value; const value = result[i][j].value; if (rowSpanName === value && i > 0) { if (!result[i][j - 1] || prevSame(result, i, j, startRowIndex)) { let { rowspan } = result[startRowIndex][j]; result[startRowIndex][j].rowspan = rowspan ? rowspan + 1 : 2; result[i][j].hidden = true; } else { startRowIndex = i } } else { startRowIndex = i } } }
return result.map(v => ({ data: v, key: v.map(v => v.value).join('') })); } }, computed: { tableData() { return this.handleTableData(this.tableBody, this.tableHead) } } } </script>
<style scoped> h2 { margin: 20px 0 } table, th, td { border: 1px solid black; border-collapse: collapse; } th, td { padding: 10px; } </style>
|