最近做项目遇到一个奇葩需求,就是table中前五列是固定的后面列数不固定(可能一列或十列)。所以这里需要用到动态表头。实现后的效果如下:
具体实现如下:
1.for 循环动态表头的对象
<!--动态表头 根据后端返回展示多少个字段-->
<el-table-column v-for="(item, index) in tableTitle" :prop="item.lable" :label="item.shopName" :key="index"></el-table-column>
data中定义动态列的数组对象
export default{
name:'',
data(){
tableTitle: [{ shopName: '字段1',lable :'supplidName'}, { shopName: '字段2',lable :'maxDate' }, { shopName: '字段3',lable :'avgPrice' }],
}
}
初始化页面钩子函数中加载请求列表方法
created() {
this.getList();
},
2.将动态查询的表头值赋值给主table;
需要对后台数据进行处理(注意图中标注的地方)
上图是接口返回,需要处理成下面这样的JSON即可
getList() {
this.loading = true;
getbpPoStaticsView(this.queryParams).then(response => {
response.rows.forEach(item => {
item['attr'] = [];
item['isGetAttr'] = false;//是否已展开清单
let objPrices = item.arrayPrices;// rows[i].arrayPrices 字段对应的值 {price_1: 22}
let newobj = Object.entries(objPrices).map(([lable,shopName]) => ({lable,shopName}));//将对象转换为数组对象 可取出key value的值 {} [{},{}]
// console.log('前',objPrices,'后',newobj);
// 拼接字段和值赋值给主table
newobj.map(itea => {
// 关键行 把动态列表和table字段一一对应上 才能展示
item[itea.lable] = itea.shopName;
})
});
this.tableTitle = response.headers;//获取动态列 【表头和字段】 headers:{lable: "price_1", shopName: "价1"}; lable指动态列数据字段名 shopName指动态列表头名
console.log('返回的动态列表是=》',this.tableTitle);
this.wipList = response.rows;
this.total = response.total;
this.loading = false;
});
},