需求:
根据所选月份,异步获取月份数据,渲染生成动态表头、表格。主要思路是根据Ant-Table表头分组用法:columns[n]
可以内嵌 children
,以渲染分组表头,进行分组。
难点:
1.获取monthRate中月份;2.根据monthRate中的key,显示对应的value,其中使用dataIndex的时候,table表中不显示对应的value值,因此又使用了customRender函数进行渲染获取。
dataIndex: `monthRate.${month}`,
key: `monthRate.${month}`,
customRender: function({ record }) {
const { monthRate } = record
const monthRateValue = monthRate[month]
return h('div', monthRateValue)
}
相关描述信息如下:
1.异步获取数据格式如下:
{
"freeTime": 299.5000,
"idleRate": "59.6000%",
"monthRate": {
"202402": "59.1300%",
"202401": "60.0000%"
}
}
2.页面最终样式如下图所示:
3.相关代码:
<template>
<!-- 查询表单 -->
<!-- 导出按钮 -->
<!-- table表 -->
<pro-table
ref="tableRef"
header-title="员工工作情况统计"
row-key="id"
:data-source="dataSource"
:columns="dynamicColumns"
:scroll="{ x: 1800 }"
:pagination="false"
>
</pro-table>
</template>
<script setup lang="ts">
//引入部分
//异步获取数据
const monthRate = ref({})
const dataSource = ref<Array<PageVO>>([])
const dataRequest = () => {
doRequest(pageGet({ ...searchParams }), {
onSuccess: res => {
const resData = res.data;
// 清空并重新填充 dataSource
dataSource.value.splice(0, dataSource.value.length);
dataSource.value.push(...resData);
// 更新月份数据
monthRate.value = resData.reduce((acc, item) => {
Object.keys(item.monthRate).forEach(month => {
if (!acc[month]) {
acc[month] = true;
}
});
return acc;
}, {})
// 输出动态生成的表头
generateColumns();
},
});
};
const dynamicColumns = ref()
const generateColumns = () => {
dynamicColumns.value = [
{
title: '空闲天数',
dataIndex: 'freeTime',
width: 100,
align: 'center'
},
{
title: '空闲率',
dataIndex: 'idleRate',
width: 100,
align: 'center',
children: [
{
title: '总空闲率',
dataIndex: 'idleRate',
key: 'idleRate',
align: 'center',
width: 100,
},
// 动态生成月份表头
...Object.keys(monthRate.value).map(month => ({
title: month,
dataIndex: `monthRate.${month}`,
key: `monthRate.${month}`,
width: 100,
align: 'center',
customRender: function({ record }) {
const { monthRate } = record
const monthRateValue = monthRate[month]
return h('div', monthRateValue)
}
})),
],
},
];
};
// 监听 monthRate 的变化,生成动态表头
watch(monthRate, () => {
generateColumns();
});