vue3 + Ant Design 实现双表头表格的效果(横向表头+纵向表头)
作者:十五圆
这篇文章主要介绍了vue3 + Ant Design 实现双表头表格(横向表头+纵向表头),需要的朋友可以参考下
一、要实现的效果(纵向固定表头的表格,横向表头数量动态化)

二、这是后台返回的数据格式(以企业为数组,每个企业里有个站点数组pointFactors)

三、代码实现步骤
(1)定义纵向固定表头
// 纵向表头数组 tableColumns
const tableColumns = ref([
{
label: "日(24小时)数据浓度均值",
value: "monthMaxDayValue",
},
{
label: "小时数据平均浓度均值",
value: "monthHourValue",
},
]);(2)动态生成横向表头(从接口获取数据)
//定义横向表头列 columns
const columns = ref([]);
//定义表格数据
const list = ref([]);
// 先添加第一列
columns.value = [
{
title: "",
dataIndex: "timeType",
width: 190,
fixed: "left",
},
];
//处理接口返回的数据data,动态拼接表头数组 columns
data.forEach(item => {
const obj = {
id: item.enterpriseId,
parentId: null,
title: item.enterpriseName,
align: "center",
children: [],
};
if (item.pointFactors.length) {
item.pointFactors.forEach(element => {
list.push({
name: element.pointName,
id: element.pointId,
monthMaxDayValue: element.monthMaxDayValue,
monthHourValue: element.monthHourValue,
});
const childObj = {
id: element.pointId,
parentId: item.enterpriseId,
title: element.pointName,
width: 130,
align: "center",
dataIndex: element.pointId,
customRender: ({ record }) => {
return record[element.pointId]
? record[element.pointId]
: "-";
},
};
obj.children.push(childObj);
});
}
columns.value.push(obj);
});(3)循环原始数据,生成组件需要的横向数据
// tableColums 已定义的纵向表头
// tableData 已定义的表格数组
for (const tab of tableColumns.value) {
const col: any = Object.create(null);
list.forEach((item, index) => {
col.timeType = tab.label;
col[list[index + 0].id] = item[tab.value];
});
tableData.value.push(col);
}(4)数据带入表格组件中
<a-table
:columns="columns"
:data-source="tableData"
:pagination="false"
row-key="id"
bordered
/>到此这篇关于vue3 + Ant Design 实现双表头表格(横向表头+纵向表头)的文章就介绍到这了,更多相关vue Ant Design双表头表格内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
