vue+element 动态的计算表格中的单元格的宽度

需求是这样的,之前我也写过,就是前端渲染的表格数据是动态渲染表格的行和列,

那么就必然出现了一个问题,当列超过一定的个数的时候,会出现横向滚动条,

那么怎么让表格整体看起来自然协调一些呢,老大要求表格的单元格宽度根据内容动态计算,最大200px,

so 干吧

template代码:

min-width要动态设置

 1 <template v-for="(item,i) in table.titleData">
 2           <el-table-column
 3             :min-width="item.columnWidth"
 4             show-overflow-tooltip
 5             :key="i"
 6             v-if="item.is_show == '1'"
 7             :prop="item.field_code"
 8             :label="item.field_title"
 9             align="center"
10           ></el-table-column>
11         </template>

script代码:

在获取到表格数据的时候,为每个数据对象设置 columnWidth 属性,初始值为50px,

然后在执行 tableWidthAdaptation 方法,这个方法是关键

 1 if (error == 0) {
 2         // 遍历title_list,将columnWidth:50px写入每个对象中
 3         for(let i in title_list) {
 4           title_list[i].columnWidth = '50px'
 5         }
 6         this.table.groupSearchList = group_list;
 7         this.table.titleData = title_list;
 8         this.table.tables = list;
 9         this.table.total = count;
10         this.table.currentPage = res.data.result.page; //当前页
11         setTimeout(function() {
12           _this.tableWidthAdaptation();
13         },100);
14       }
 1 tableWidthAdaptation() {
 2       let rows = this.$refs.tableData.$el.childNodes[2].childNodes[0].childNodes[1].rows;
 3       // console.log(rows)
 4       let arr = [];
 5       for (let i = 0; i < rows.length; i++) {
 6         for (let j = 0; j < rows[i].cells.length; j++) {
 7             let w = rows[i].cells[j].childNodes[0].offsetWidth;
 8             // 判断w值 如果小于50 则 为50px,大于200则为200px,其他的为w+12px
 9             if (w < 50) {
10               w = 50 + "px";
11             } else if (w > 200) {
12               w =  200 + "px";
13             } else {
14               w =  w + 12 + "px";
15             }
16             if (!arr[j] || arr[j] < w) {
17               arr[j] = w;
18             }
19         }
20       }
21       let titleData = this.table.titleData
22       // 遍历titleData 将得到的宽度写到titleData 的字段中
23       for (let z = 0; z < titleData.length; z++) {
24         const value = titleData[z];
25         value.columnWidth = arr[z]
26       }
27     },
let rows = this.$refs.tableData.$el.childNodes[2].childNodes[0].childNodes[1].rows; 获取到了表格的每一行数据
然后通过遍历,得到每一个单元格的宽度 let w = rows[i].cells[j].childNodes[0].offsetWidth;
最后将值赋值到 titleData 中,页面for循环赋值到min-width上面

猜你喜欢

转载自www.cnblogs.com/jun-qi/p/10931356.html