Vue.js+Element UI实现二维表格展示源数据
1.WebAPI接收的数据是这个样子的:
[{"项目":"营业成本","年份":"2022","数额":"5400"},{"项目":"营业成本","年份":"2021","数额":"7348"},{"项目":"营业成本","年份":"2020","数额":"5713"},{"项目":"营业成本","年份":"2019","数额":"2816"},{"项目":"营业收入","年份":"2022","数额":"6821"},{"项目":"营业收入","年份":"2021","数额":"7775"},{"项目":"营业收入","年份":"2020","数额":"7881"},{"项目":"营业收入","年份":"2019","数额":"7834"},{"项目":"固定支出","年份":"2022","数额":"810"},{"项目":"固定支出","年份":"2021","数额":"732"},{"项目":"固定支出","年份":"2020","数额":"721"},{"项目":"固定支出","年份":"2019","数额":"610"}]
2.但是想要的效果一个二维表格:
3.这时候需要做个简单的处理,直接上代码:
<template>
<el-table :header-cell-style="{background:'#f2f2f2',color:'#666',fontWeight:'bold',fontSize:'16px'}" :data="listTagClass" style="width: 100%; margin-top: 20px" border> <el-table-column prop="项目" label="项目*年份" align="center"></el-table-column> <el-table-column v-for="item in this.listYears" align="center" :key="item.id" :label="item.label"> <template slot-scope="scope"> <span v-for="(i, index) in scheduleList" :key="index"> <span style="width:60" v-if="scope.row.项目===i.项目 && item.年份===i.年份"> <div>{{ i.数额 }}</div> </span> </span> </template> </el-table-column> </el-table>
<script>
export default { data () { return { scheduleList: [], listTagClass: [], listYears: [], ... } }, created() { // 在初始化的时候进行获取 this.fetchData() }, methods: { async fetchData() { var url = `/*这里是webapi获取数据的url*/` this.scheduleList = await (await fetch(url)).json() let _this = this; for (let i = 0; i < this.scheduleList.length; i++) { let hasSameName = false; hasSameName = this.listTagClass.some(function (item) { if (item.项目 === _this.scheduleList[i].项目) { return true; } }) if (!hasSameName) { this.listTagClass.push({ 项目: _this.scheduleList[i].项目 }) } let hasSameYear = false; hasSameYear = this.listYears.some(function (item) { if (item.年份 === _this.scheduleList[i].年份) { return true; } }) if (!hasSameYear) { this.listYears.push({ id: Math.floor(Math.random() * 9999999999 + 1), label: _this.scheduleList[i].年份, 年份: _this.scheduleList[i].年份, 项目: _this.scheduleList[i].项目, 数额: _this.scheduleList[i].数额 }) } } } } }