vue3 + Ant Design 实现双表头表格(横向表头+纵向表头)

  • vue3 + Ant Design 实现双表头表格(横向表头+纵向表头)已关闭评论
  • 95 次浏览
  • A+
所属分类:Web前端
摘要

 一、要实现的效果( 纵向固定表头的表格,横向表头数量动态化 ) 二、这是后台返回的数据格式(以企业为数组,每个企业里有个站点数组pointFactors)

 一、要实现的效果(纵向固定表头的表格,横向表头数量动态化

vue3 + Ant Design 实现双表头表格(横向表头+纵向表头)

二、这是后台返回的数据格式(以企业为数组,每个企业里有个站点数组pointFactors)

 vue3 + Ant Design 实现双表头表格(横向表头+纵向表头)

三、代码实现步骤

 (1)定义纵向固定表头

 1 // 纵向表头数组 tableColumns  2 const tableColumns = ref([  3   {  4     label: "日(24小时)数据浓度均值",  5     value: "monthMaxDayValue",  6   },  7   {  8     label: "小时数据平均浓度均值",  9     value: "monthHourValue", 10   }, 11 ]);

 (2)动态生成横向表头(从接口获取数据

 1 //定义横向表头列 columns  2  const columns = ref([]);  3 //定义表格数据  4  const list = ref([]);   5   6  // 先添加第一列  7  columns.value = [  8       {  9         title: "", 10         dataIndex: "timeType", 11         width: 190, 12        fixed: "left", 13      }, 14   ]; 15  16 //处理接口返回的数据data,动态拼接表头数组 columns 17 data.forEach(item => { 18      const obj = { 19         id: item.enterpriseId, 20         parentId: null, 21         title: item.enterpriseName, 22         align: "center", 23         children: [], 24       }; 25       if (item.pointFactors.length) { 26           item.pointFactors.forEach(element => { 27               list.push({ 28                 name: element.pointName, 29                 id: element.pointId, 30                 monthMaxDayValue: element.monthMaxDayValue, 31                 monthHourValue: element.monthHourValue, 32               }); 33               const childObj = { 34                 id: element.pointId, 35                 parentId: item.enterpriseId, 36                 title: element.pointName, 37                 width: 130, 38                 align: "center", 39                 dataIndex: element.pointId, 40                 customRender: ({ record }) => { 41                   return record[element.pointId] 42                     ? record[element.pointId] 43                     : "-"; 44                 }, 45               }; 46               obj.children.push(childObj); 47           }); 48      } 49      columns.value.push(obj); 50 });

 (3)循环原始数据,生成组件需要的横向数据

 1 // tableColums  已定义的纵向表头  2 // tableData   已定义的表格数组  3   4  for (const tab of tableColumns.value) {  5      const col: any = Object.create(null);  6   7      list.forEach((item, index) => {  8          col.timeType = tab.label;  9          col[list[index + 0].id] = item[tab.value]; 10      }); 11      tableData.value.push(col); 12 }

(4)数据带入表格组件中

 <a-table      :columns="columns"      :data-source="tableData"      :pagination="false"      row-key="id"      bordered  />