场景描述
在实际开发过程中,部分表头是根据页面中的某个参数动态生成的,常见于报表类;
需求分析
思路
<template>
<div>
<div class="btnWrap">
<el-button @click="edit = !edit">编辑</el-button>
</div>
<el-table
:header-row-style="{background:'#ECF6FF',color:'#041D4B'}"
:row-style="{fontFamily:'MicrosoftYaHei',fontSize: '13px',color:'#333333'}"
:header-cell-style="{background:'#ECF6FF',color:'#041D4B'}"
class="crmonepage-hello"
ref="tabled"
:data="list"
:border="true"
header-align="center"
style="width: 100%">
<el-table-column
v-for="(col,index) in cols"
:label="col.label"
:key="index"
:min-width="col.width || null"
:prop="col.prop"
align="center"
>
<el-table-column
v-for="(child, childIndex) in col.propsChildren"
:label="child.label"
:key="childIndex"
:min-width="child.width || null"
:prop="child.prop"
align="center"
>
<template slot-scope="scope">
<el-input-number v-model="scope.row[child.prop]" :controls="false" v-if="edit"> </el-input-number>
<span v-else>{{scope.row[child.prop]}}</span>
</template>
</el-table-column>
</el-table-column>
</el-table>
</div>
</template>
<script>
export default {
data(){
return{
edit:false,
//表格数据
list: [
{username: "北京某科技公司",area: "朝阳区",voltageClass: "220",capacity: "150",maxLoad2015: 11,yearPower2015: 12,operationalCapacity2015: 13,maxLoad2016: 11,yearPower2016: 12,operationalCapacity2016: 13},
{username: "北京某学校",area: "海淀区",voltageClass: "220",capacity: "350",maxLoad2015: 11,yearPower2015: 12,operationalCapacity2015: 13,maxLoad2016: 11,yearPower2016: 12,operationalCapacity2016: 13},
],
// 表头数据
cols: [
{prop: "username",label: "用户名称", width: 150},
{prop: "area",label: "所属地区", width: 150},
{prop: "voltageClass",label: "电压等级(kV)", width: 150},
{prop: "capacity",label: "预计报装容量(MVA)",width: 150},
{prop: "power2015",label: "2015",width: 150,propsChildren: [
{prop: "maxLoad2015",label: "最大负荷(MW)",width: 150},
{prop: "yearPower2015",label: "年用电量(亿kWh)",width: 150},
{prop: "operationalCapacity2015",label: "预计投运容量(MVA)",width: 150},
]
},
{prop: "power2016",label: "2016",width: 150,propsChildren: [
{prop: "maxLoad2016",label: "最大负荷(MW)",width: 150},
{prop: "yearPower2016",label: "年用电量(亿kWh)",width: 150},
{prop: "operationalCapacity2016",label: "预计投运容量(MVA)",width: 150},
]
},
]
}
}
}
</script>
<style scope lang="scss">
.btnWrap{
margin-bottom: 10px;
}
</style>
动态表头代码实现
this.peopleHistoryColumnHeader = [];//动态表头集合
var obj ;
yearList.forEach(year =>{
obj = {
prop:'power'+ year, label: year, width: 180,
propsChildren:[
{prop: 'maxLoad'+ year, label:"最大负荷(MW)",width: 180},
{prop: 'maxPower'+ year, label:"年用电量(亿kWh)",width: 180},
]
};
this.peopleHistoryColumnHeader.push(obj);
})
if(peopleHistoryData == null){
this.peopleHistoryData = [];
var power = {};//动态年份数据
yearList.forEach(year =>{
power['maxLoad'+ year] = undefined;
power['maxPower'+ year] = undefined;
})
this.peopleHistoryData.push({
rowId: Math.random(),
username: '',
area:'',
voltageClass: '',
capacity: undefined,
removeTime: '',
type: '',
...power
})
}