前言

此文主要记录el-table循环表头以及数据时,对于后台返回不规则数据如何处理的问题。

形如:

1
2
3
4
5
6
7
8
9
10
11
12
data: [
[
{ "id": null,"fieldName": "姓名", "fieldNameValue": "小明"},
{ "id": null,"fieldName": "姓名", "fieldNameValue": "小红"},
{ "id": null,"fieldName": "姓名", "fieldNameValue": "小黄" }
],
[
{ "id": null,"fieldName": "年龄", "fieldNameValue": "18"},
{ "id": null, "fieldName": "年龄", "fieldNameValue": "17"},
{ "id": null,"fieldName": "年龄", "fieldNameValue": "25"}
]
]

遇到这种不规则的数据 可以试着使用下列的方式处理。

模板中的代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<el-table :data="tableData" border>
<el-table-column
v-for="col in columns"
:key="col.prop"
:label="col.label">
<template #default="{ row, column, $index }">
<el-input
v-if="isEditable"
v-model="row[col.prop]"
size="small"
></el-input>
<span v-else>{{ row[col.prop] }}</span>
</template>
</el-table-column>
</el-table>

Script模板中对应的数据处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
const columns = ref([]);
const tableData = ref([]);
const isEditable = ref(false);

const processData = (response) => {
// 生成列信息 response 为后台请求成功后返回的数据
const fields = response.data.map(column => column[0].fieldName);
const columnsData = fields.map(field => ({ prop: field, label: field }));
columns.value = columnsData;

// 生成表格数据
const numRows = response.data[0].length;
const data = Array.from({ length: numRows }, (_, rowIndex) => {
const row = {};
response.data.forEach(column => {
row[column[0].fieldName] = column.find(item => item.index === rowIndex)?.fieldNameValue || '';
});
return row;
});
tableData.value = data;
};