赞
踩
本文主要解决场景:表头不固定、从后端数据中拿取表头并渲染到页面中。
let data = {
"header": [
"单位名称",
"单位简称"
],
"rows": [
{
"row": [
"公司1"
],
},
{
"row": [
"公司2"
]
}
]
}
其中headers则为表头数组,而rows则为表内容。有朋友会发现,这里的表内容并不是对象格式,所以这里我在下面又做了一些拼接和数据处理。
获取到数据后,我需要对这些数据进行分别处理存储后才能使用。如下代码所示
const Header = ref([])
const bodyData = ref([])
const handleData = () =>{
Header.value = data.header
bodyData.value = data.rows.reduce((acc,row,rowIndex)=>{
if(rowIndex % Header.value.length === 0) {
acc.push({});
}
const newRow = acc[acc.length - 1];
const columnName = Header.value[rowIndex % Header.value.length];
newRow[columnName] = row.row[0];
return acc
},[])
}
这段代码使用 reduce 方法来处理 data.rows 数组,并根据 Header 的值构建新的数据结构。
Reduce 函数接收一个回调函数和初始值(这里是空数组 [])。
回调函数有三个参数:累计器 acc、当前元素 row 和当前索引 rowIndex。
当 rowIndex 能被 Header 长度整除时(即开始新行时),向累计器 acc 中添加一个新的空对象。
获取最新的空对象,并将其赋值给 newRow。
计算当前列名:通过 rowIndex 对 Header 长度取模得到。
填充数据:将 row.row[0] 的值以当前列名为键,存入 newRow。
最终返回acc累计器。
表头获取到的数据示例:
[
"姓名",
"年龄"
]
列数据获取到的数据示例:
[
{
"姓名": "梨花",
"年龄": "18"
}
]
<el-table :data="bodyData" max-height="500" border>
<el-table-column v-for="(item, index) in Header" :key="index" :label="item" show-overflow-tooltip
align="center" :min-width="index === 0 ? '120' : ''" :fixed="index === 0">
<template #default="scope">
<span>{{ scope.row[item] }}</span>
</template>
</el-table-column>
</el-table>
在代码中,我们渲染的数据为bodyData,我们在colunm中我们循环遍历Header表头,并将label设置为item,最后我们在插槽中,获取根据表头名称来获取当前列下的每条数据的值。
{
"body": [
{
"name": "梨花",
"age": 18
},
{
"name": "丽丽",
"age": 18
}
],
"header": [
"name",
"age"
]
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。