< template> < div class = " index-wapper" > < el-table :data = " tableData" :span-method = " objectSpanMethod" border > < el-table-column v-for = " (item, index) in tableHeader" :key = " index" :prop = " item.prop" :label = " item.label" :fixed = " item.fixed" align = " center" > </ el-table-column> </ el-table> </ div>
</ template>
< script>
export default { name : "index-page" , components : { } , props : { } , data ( ) { return { tableHeader : [ { prop : "country" , label : "城市" , fixed : true , } , { prop : "title" , label : "地区" , fixed : true , } , { prop : "data1" , label : "1" , fixed : false , } , { prop : "data2" , label : "2" , fixed : false , } , { prop : "data3" , label : "3" , fixed : false , } , { prop : "data4" , label : "4" , fixed : false , } , { prop : "data5" , label : "5" , fixed : false , } , ] , tableData : [ { id : 1 , country : "杭州" , title : "滨江" , data1 : 0 , data2 : 1 , data3 : 0 , data4 : 1 , data5 : 0 , } , { id : 2 , country : "杭州" , title : "西湖" , data1 : 0 , data2 : 0 , data3 : 0 , data4 : 0 , data5 : 0 , } , { id : 3 , country : "杭州" , title : "余杭" , data1 : 0 , data2 : 1 , data3 : 0 , data4 : 1 , data5 : 1 , } , { id : 4 , country : "长沙" , title : "岳麓" , data1 : 0 , data2 : 0 , data3 : 0 , data4 : 0 , data5 : 1 , } , { id : 5 , country : "长沙" , title : "开福" , data1 : 1 , data2 : 1 , data3 : 0 , data4 : 1 , data5 : 0 , } , ] , spanArr : [ ] , } ; } , mounted ( ) { this . getSpanArr ( ) ; } , methods : { getSpanArr ( ) { const hLen = this . tableHeader. length; for ( let i = 0 ; i < this . tableData. length; i++ ) { if ( i === 0 ) { for ( let j = 0 ; j < hLen; j++ ) { this . spanArr[ i * hLen + j] = { rowspan : 1 , colspan : 1 , } ; } } else { for ( let j = 0 ; j < hLen; j++ ) { if ( this . tableHeader[ j] . prop === "country" ) { if ( this . tableData[ i] [ "country" ] !== this . tableData[ i - 1 ] [ "country" ] ) { this . spanArr[ i * hLen + j] = { rowspan : 1 , colspan : 1 , } ; } else if ( this . tableData[ i] [ this . tableHeader[ j] . prop] === this . tableData[ i - 1 ] [ this . tableHeader[ j] . prop] ) { let beforeItem = this . spanArr[ ( i - 1 ) * hLen + j] ; this . spanArr[ i * hLen + j] = { rowspan : 1 + beforeItem. rowspan, colspan : 1 , } ; beforeItem. rowspan = 0 ; beforeItem. colspan = 0 ; } else { this . spanArr[ i * hLen + j] = { rowspan : 1 , colspan : 1 , } ; } } } } } let stack = [ ] ; for ( let i = 0 ; i < hLen; i++ ) { for ( let j = 0 ; j < this . tableData. length; j++ ) { const spanItem = this . spanArr[ j * hLen + i] ; if ( spanItem) { if ( spanItem. rowspan === 0 ) { stack. push ( spanItem) ; } if ( j !== 0 && spanItem. rowspan !== 0 ) { stack. push ( spanItem) ; while ( stack. length > 0 ) { let pop = stack. pop ( ) ; let len = stack. length; this . spanArr[ ( j - len) * hLen + i] = pop; } } } } } } , objectSpanMethod ( { rowIndex, columnIndex } ) { return this . spanArr[ rowIndex * this . tableHeader. length + columnIndex] ; } , } , watch : { } ,
} ;
< / script>