业务功能:
根据开始,结束月份选择实现动态表头
实现页面:
后端返回数据格式:
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>
相关文章
暂无评论...