前端页面使用的vue的element-ui。需要实现的需求如下图:用户页面选择起始运距和运距间隔后,服务器动态生成运距和对应的运输车数列表。
element table组件的render-header函数属性。 这个函数是专门用作渲染表格的列表头的。用法如下:
1.在data区定义header
data{
return{
//动态列头header header:[] } }
2.设置表格属性:render-header="labelHead",函数名 labelHead 可以自己起名。
<el-table v-if="wideTable" v-loading="loading" :data="checkLogList" :render-header="labelHead" :border="true">
3.写render-header的回调函数。请忽略下面的注释,但是,返回值必须是要h(‘span‘,)这个格式的,关于这个函数的具体研究可以参考这里 https://segmentfault.com/a/1190000016364550,查看vue的官方文档
labelHead(h,{column,index}){ //动态表头渲染 //let l = column.label.length; //let f = 12; //每个字大小,其实是每个字的比例值,大概会比字体大小打差不多大 //column.minWidth = f * l; //字大小乘个数即长度 ,注意不要加px像素,这里minWidth只是一个比例值,不是真正的长度 //然后将列标题放在一个div块中,注意块的宽度一定要100%,否则表格显示不完全 return h(‘span‘,{class:‘table-head‘,style:{width:‘100%‘}},[column.label]) }
4.在你需要header的方法里把后台返回的数据填充到header里。
methods: { /** 查询用户列表 */ getList() { this.loading = true; listCheckLog(this.addDateMonth(this.queryParams, this.month)).then(response => { this.checkLogList = response.rows; // 在这里将后台返回的列表头数据直接放到之前定义好的header数组中 this.header = this.checkLogList[0].header; this.total = response.total; this.loading = false; } ); }
}
5.最关键的是在需要生成动态列的地方遍历header数组,生成列。同时在行内遍历与表头具有对应关系的另一个数据填充列表。在index相等的时候将数据填充到对应的列下
<el-table-column :label="item" v-for="(item, index) in header" :key="item" align="center"> <template slot-scope="scope"> <span v-for="(item2,index2) in scope.row.transportNumByDistance" v-if="index2 == index"> {{ scope.row.transportNumByDistance[index2].transportNum }} </span> </template> </el-table-column>
原文:https://www.cnblogs.com/netcore-vue/p/14849492.html