这是一个根据数据中相同key值进行比对从而实现table跨行合并的demo。最主要还是想练练递归。也正好解决一个网友的问题。
table的html部分:
<template>
<div>
<table cellspacing="0" cellpadding="0" border="0" style="height: auto; width: 100%">
<thead>
<tr>
<th>row1</th>
<th>row2</th>
<th>row3</th>
<th>row4</th>
</tr>
</thead>
<tbody>
<tr v-for="(item,index) in dealRowspan()" :key="index">
<td :rowspan="item.row1Rowspan" v-if="item.row1Show">{{ item.row1 }}</td>
<td :rowspan="item.row2Rowspan" v-if="item.row2Show">{{ item.row2}}</td>
<td :rowspan="item.row3Rowspan" v-if="item.row3Show">{{ item.row3}}</td>
<td :rowspan="item.row4Rowspan" v-if="item.row4Show">{{ item.row4}}</td>
</tr>
</tbody>
</table>
</div>
</template>
css部分:
<style scoped>
table {
width: 600px;
border: 1px solid #ccc;
border-collapse: collapse;
}
thead th {
text-align: left;
background-color: #fafafa;
}
th,td {
padding-left: 20px;
border: 1px solid #e9eaec;
line-height: 30px;
height: 50px;}
</style>
js部分:
export default{
data() {
return {
testTableData:[
{
row1:'南京',
row2:'无锡',
row3:'盐城',
row4:'杭州',
},
{
row1:'南京',
row2:'无锡',
row3:'盐城',
row4:'常州',
},
{
row1:'上海',
row2:'无锡',
row3:'盐城',
row4:'杭州',
},
{
row1:'上海',
row2:'苏州',
row3:'盐城',
row4:'合肥',
},
{
row1:'上海',
row2:'苏州',
row3:'台州',
row4:'常州',
},
],
};
},
method:{
dealRowspan(){//获取处理之后的新的数据
if(this.testTableData.length==0){
return this.testTableData
}
let startIndex = 0;
Object.keys(this.testTableData[0]).forEach(key=>{
this.recursiveFn(startIndex,key,this.testTableData)
})
return [...this.testTableData]
},
recursiveFn(startIndex,key,testTableData){//递归处理数据
if(startIndex==testTableData.length){
return
}
for (let index = startIndex; index < testTableData.length; index++) {
testTableData[index][`${key}Rowspan`]=1;
testTableData[index][`${key}Show`]=false;
if(!testTableData[index+1]||testTableData[index][key]!=testTableData[index+1][key]){
testTableData[startIndex][`${key}Rowspan`]=index-startIndex+1;
testTableData[startIndex][`${key}Show`]=true;
startIndex=index+1
break
}
}
if(startIndex<testTableData.length){
this.recursiveFn(startIndex,key,testTableData)
}
}
}
最终效果:
TIME