需求是這樣的,以前我也寫過,就是前端渲染的表格數據是動態渲染表格的行和列,前端
那麼就必然出現了一個問題,當列超過必定的個數的時候,會出現橫向滾動條,數組
那麼怎麼讓表格總體看起來天然協調一些呢,老大要求表格的單元格寬度根據內容動態計算,最大200px,this
so 幹吧spa
template代碼:3d
min-width要動態設置code
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,blog
而後在執行 tableWidthAdaptation 方法,這個方法是關鍵ip
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 }