// el-table 列數(shù)據(jù)
data(){
return{
tableColumn : [
{
label: "物料名稱",
prop: "materialName",
width: 150
},
{
label: "色名",
prop: "colorName",
width: 150
},
]
}
},
// 獲取列寬度 tableData: 接口返回表格數(shù)據(jù),label: 表頭名字,columnKey: 列表對應(yīng)字段
getColumnWidth(tableData,label,columnKey){
const arr = tableData.map(x => x[columnKey])
arr.push(label) // 把每列的表頭也加進去算
// 獲取列中最長的字符長度
let text = this.findLongestElement(arr)
const chineseLeg = this.countCharacters(text).chineseCount || 0
const digitLeg = this.countCharacters(text).digitCount || 0
const englishLeg = this.countCharacters(text).englishCount || 0
// 根據(jù)字符長度設(shè)置列寬,可以根據(jù)具體需求進行調(diào)整
const maxLength = (chineseLeg * 14) + (digitLeg * 9) + (englishLeg * 12) ;
const minWidth = 90; // 最小列寬
const padding = 30; // 額外的內(nèi)邊距
return `${Math.max(minWidth, maxLength + padding)}px`;
},
// 獲取最長字符有多少漢字/數(shù)字/英文
countCharacters(str) {
const chinesePattern = /[\u4e00-\u9fa5]/g; // 匹配漢字的正則表達式
const digitPattern = /\d/g; // 匹配數(shù)字的正則表達式
const englishPattern = /[a-zA-Z]/g; // 匹配英文字符的正則表達式
const chineseCount = (str.match(chinesePattern) || []).length;
const digitCount = (str.match(digitPattern) || []).length;
const englishCount = (str.match(englishPattern) || []).length;
return { chineseCount, digitCount, englishCount };
},
// 獲取最長的一個字符
findLongestElement(arr) {
if (arr.length === 0) {
return null; // 如果數(shù)組為空,返回null或者其他適當(dāng)?shù)闹? }
// 使用 reduce 方法找到最長的元素
const longestElement = arr.reduce((longest, current) => {
if (String(current).length == String(longest).length) { // 如果長度相等 選取漢字多的字符為標準
const chineseLeg = this.countCharacters(String(current)).chineseCount || 0
const chineseLeg2 = this.countCharacters(String(longest)).chineseCount || 0
return chineseLeg2 < chineseLeg ? String(current) : String(longest);
} else {
return String(current).length > String(longest).length ? String(current) : String(longest);
}
}, arr[0]);
return longestElement;
}
// 使用
this.tableColumn.forEach(item => {
item.width = this.getColumnWidth(res.data.records,item.label,item.prop)
})
表格列寬自適應(yīng)
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
相關(guān)閱讀更多精彩內(nèi)容
- 前言 對于動態(tài)獲取數(shù)據(jù)的表格,如果期望單元格內(nèi)容不折行,就要設(shè)定足夠的寬度,同時又希望表格內(nèi)容盡量緊湊,但是,由于...
- 由于項目的需求規(guī)定表格中的內(nèi)容超出部分不能懸浮顯示,要自適應(yīng)寬,先element 表格的是不支持自適應(yīng)的,經(jīng)過搜索...
- 兩種方法:方法一、計算文本內(nèi)容寬度,遍歷第一行數(shù)據(jù),取最寬的值,設(shè)置width屬性計算文本有兩種方法計算方法1,使...
- template data methods 原文鏈接:https://blog.csdn.net/qq_33235...
- 在<nz-table>標簽加上拖拽指令tableColumnWidthDrag即可生效, 注意必須包含 標簽, ...