根据字段进行多个单元格合并
适用于动态数据且多个需要合并的
效果图:
代码:
<template>
<a-table
bordered
:columns="columns"
:data-source="mergeData(data,['age','phone'])"
/>
</template>
<script>
const columns = [
{
title: 'recordName',
dataIndex: 'recordName',
},
{
title: 'Age',
dataIndex: 'age',
customRender: (value, row) => {
const obj = {
children:value,
attrs: {}
};
obj.attrs.rowSpan = row.ageRowNum;
return obj;
}
},
{
title: 'Phone',
dataIndex: 'phone',
customRender: (value, row) => {
const obj = {
children:value,
attrs: {}
};
obj.attrs.rowSpan = row.phoneRowNum;
return obj;
}
},
{
title: 'Address',
dataIndex: 'address',
},
];
const data = [];
for (let i = 0; i < 5; i++) {
data.push({
key: i,
recordName: `Edward King ${i}`,
age: 32,
phone:1234567,
address: `London, Park Lane no. ${i}`,
});
}
export default {
data() {
return {
data,
columns,
};
},
methods:{
//data:表单的数据
//mergeField:要合并的列
mergeData(data,mergeField){
mergeField.forEach(item=>{
let recordList,recordName;
for (let i = 0; i < data.length; i++){
let currentRow = data[i][item]; //当前行
let preRow = i ? data[i - 1][item] :"";//上一行
if(i == 0 || currentRow != preRow){ //第一行无需比较 当前行与上一行不相同
data[i][item+"RowNum"] = 1; //rowSpan设置为1
recordList = data[i]; //记录当前的数据
recordName = [item+"RowNum"];
}else if(currentRow === preRow){ //当前行与上行相同
data[i][item+"RowNum"] = 0; //设置当前行数为0
recordList[recordName] += 1; //将刚才记录的数据 进行+1
}
}
})
return data;
},
}
};
</script>
表单是自动撑开的,显着这两列格外的难看 设置列宽
可通过设置width属性或class属性
修改后效果图:
代码:
const columns = [
{
title: 'recordName',
dataIndex: 'recordName',
},
{
title: 'Age',
dataIndex: 'age',
100,
customRender: (value, row) => {
const obj = {
children:value,
attrs: {}
};
obj.attrs.rowSpan = row.ageRowNum;
return obj;
}
},
{
title: 'Phone',
dataIndex: 'phone',
className:"setLine",
customRender: (value, row) => {
const obj = {
children:value,
attrs: {}
};
obj.attrs.rowSpan = row.phoneRowNum;
return obj;
}
},
{
title: 'Address',
dataIndex: 'address',
},
];
<style scoped>
/deep/.setLine{
50px;
}
</style>