如何使用Vue.js将指定格式数据映射为表格形式?
Vue.js 实现transformedData到指定表格的映射方案
问题背景
需将给定结构的transformedData渲染为指定格式的表格,现有代码因循环层级错误、数据匹配逻辑问题,无法生成目标表格。
原始数据格式
transformedData = { missingReports: [ { empId: "1234", empName: "Aarohi", monthTotalHours: { "11-2022": { allocation: 32, totalHoursMissing: 6, difference: 21 }, "12-2022": { allocation: 91, totalHoursMissing: 3, difference: 45 } } }, { empId: "2345", empName: "Aarush", monthTotalHours: { "11-2022": { allocation:10, totalHoursMissing: 2, difference: 21 } } } ] }
期望表格输出
EmpId EmpName Nov2022al Nov2022hr Nov2022dif Dec2022al Dec2022hr Dec2022dif 1234 Aarohi 32 6 21 91 3 45 2345 Aarush 10 2 21
现有尝试代码
<template v-for="employee in transformedData"> <tr v-for="data in employee" :key="data.empId"> <td class="td-empId">{{ data.empId }}</td> <td class="td-empName">{{ data.empName }}</td> <template v-for="(date, dIndex) in getTableHeader"> <span v-for="(monthTotalHours, mIndex) in Object.values(data.monthTotalHours)" :key="mIndex"> <td :key="'TT' + dIndex">{{monthTotalHours.allocation | decimalFix}}</td> <td :key="'DD' + dIndex">{{monthTotalHours.totalHoursMissing | decimalFix}}</td> <td :key="'DDD' + dIndex">{{monthTotalHours.difference | decimalFix}}</td> </span> </template> </tr> </template>
修正后的实现方案
1. 完整模板代码
<table> <!-- 动态生成表头 --> <thead> <tr> <th>EmpId</th> <th>EmpName</th> <template v-for="date in getTableHeader" :key="date"> <th>{{ formatHeaderDate(date) }}al</th> <th>{{ formatHeaderDate(date) }}hr</th> <th>{{ formatHeaderDate(date) }}dif</th> </template> </tr> </thead> <!-- 渲染表体数据 --> <tbody> <tr v-for="employee in transformedData.missingReports" :key="employee.empId"> <td>{{ employee.empId }}</td> <td>{{ employee.empName }}</td> <!-- 按表头日期匹配对应月份数据 --> <template v-for="date in getTableHeader" :key="date"> <td>{{ (employee.monthTotalHours[date]?.allocation || '') | decimalFix }}</td> <td>{{ (employee.monthTotalHours[date]?.totalHoursMissing || '') | decimalFix }}</td> <td>{{ (employee.monthTotalHours[date]?.difference || '') | decimalFix }}</td> </template> </tr> </tbody> </table>
2. 添加日期格式化方法
在Vue组件的methods中实现日期格式转换:
methods: { formatHeaderDate(dateStr) { const [month, year] = dateStr.split('-'); const monthAbbrs = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; return `${monthAbbrs[parseInt(month) - 1]}${year}`; } }
关键修正说明
- 循环层级修正:直接遍历
transformedData.missingReports数组,避免外层无效循环。 - 精准数据匹配:根据
getTableHeader的日期字符串,直接从employee.monthTotalHours中取值,确保列与数据一一对应。 - 空值兼容:用可选链
?.处理无对应月份数据的场景,避免报错且显示空值。 - 动态表头:通过格式化方法将
11-2022转为Nov2022,保证表头与表体列对齐。
内容的提问来源于stack exchange,提问作者P.S
相关产品推荐
相关产品推荐

