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       let arr = [];
 4       for (let i = 0; i < rows.length; i++) {
 5         for (let j = 0; j < rows[i].cells.length; j++) {
 6             let w = rows[i].cells[j].childNodes[0].childNodes[0].offsetWidth;
 7             if (!arr[j] || arr[j] < w) {
 8               arr[j] = this.columnWidth(w);
 9             }
10         }
11       }
12       // 截取數組
13       arr.splice(0,2)
14       arr.splice(-1,1)
15       let titleData = this.table.titleData
16       titleData.forEach((item,i)=> {
17         item.columnWidth = arr[i]
18       })
19       this.table.titleData = titleData
20     },
21     columnWidth(value, min = 52, max = 200) {
22       value = Number(value) + 12;
23       if (value < min) {
24         return min + "px";
25       } else if (value > max) {
26         return max + "px";
27       } else {
28         return value + "px";
29       }
30     }
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上面


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM