共计 2317 个字符,预计需要花费 6 分钟才能阅读完成。
业务性能:
依据开始,完结月份抉择实现动静表头
实现页面:
后端返回数据格式:
data = [
{
"行业分类": "建筑业",
"202101": {
"数量": 6,
"占比": 20
},
"202102": {
"数量": 5,
"占比": 20
},
"202103": {
"数量": 3,
"占比": 18
},
"202104": {
"数量": 4,
"占比": 29
},
},
{
"行业分类": "租赁和商务服务业",
"202101": {
"数量": 3,
"占比": 10.0
},
"202102": {
"数量": 3,
"占比": 20.0
},
"202103": {
"数量": 2,
"占比": 20.0
},
"202104": {
"数量": 4,
"占比": 20.0
},
},
]
思路
- 后端依据前端申请月份数据返回数据
-
取出一级表头数据
let headerArray = Object.keys(Object.assign({}, ...data)) //0: "202101" //1: "202102" //2: "202103" //3: "202104" //4: "行业分类"
Object.keys 后 key 值数组乱序,数据类型不统一的独自进行排序,将数组对象中类型为 object 独自取出存储
-
只保留数组对象中是对象的数据(去除 ” 行业分类 ” 一级表头)
for (let i = 0; i < headerArray.length; i++) {if (typeof data[0][headerArray[i]] == 'object') {this.tableHeader.push(headerArray[i]) } }
-
数据渲染
<el-table style="width: 100%;" :data="tableData"> <el-table-column label="行业分类" prop="行业分类" width="150px"> </el-table-column> <template v-for="(item,index) in tableHeader"> <el-table-column :label="tableHeader[index]" :key="item"> <template v-for="(val,key,index) in tableData[0][tableHeader[index]]"> <el-table-column :label="key" :key="index" align="center"> <template> {{val}} </template> </el-table-column> </template> </el-table-column> </template> </el-table>
代码实现
<template> <div> <el-date-picker v-model="value2" type="monthrange" align="right" unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="完结日期" > </el-date-picker> <div style="padding-top: 20px"> <el-table style="width: 100%;" :data="tableData"> <el-table-column label="行业分类" prop="行业分类" width="150px"> </el-table-column> <template v-for="(item,index) in tableHeader"> <el-table-column :label="tableHeader[index]" :key="item"> <template v-for="(val,key,index) in tableData[0][tableHeader[index]]"> <el-table-column :label="key" :key="index"align="center"> <template> {{val}} </template> </el-table-column> </template> </el-table-column> </template> </el-table> </div> </div> </template> <script> export default {data() { return {tableData: [], tableHeader: [],} }, mounted() { let data = [ { "行业分类": "建筑业", "202101": { "数量": 6, "占比": 20 }, "202102": { "数量": 5, "占比": 20 }, "202103": { "数量": 3, "占比": 18 }, "202104": { "数量": 4, "占比": 29 }, }, { "行业分类": "租赁和商务服务业", "202101": { "数量": 3, "占比": 10.0 }, "202102": { "数量": 3, "占比": 20.0 }, "202103": { "数量": 2, "占比": 20.0 }, "202104": { "数量": 4, "占比": 20.0 }, }, ] this.tableData = data let headerArray = Object.keys(Object.assign({}, ...data)) console.log(headerArray) for (let i = 0; i < headerArray.length; i++) {if (typeof data[0][headerArray[i]] == 'object') {this.tableHeader.push(headerArray[i]) } } }, methods: {}} </script>
正文完