表格列寬自適應

// el-table 列數(shù)據(jù)
data(){
  return{
      tableColumn : [
        {
          label: "物料名稱",
          prop: "materialName",
          width: 150
        },
        {
          label: "色名",
          prop: "colorName",
          width: 150
        },
      ]
  }
},

 // 獲取列寬度 tableData: 接口返回表格數(shù)據(jù),label: 表頭名字,columnKey: 列表對應字段
      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ù)字符長度設置列寬,可以根據(jù)具體需求進行調整
        const maxLength = (chineseLeg * 14) + (digitLeg * 9) + (englishLeg * 12) ; 
        const minWidth = 90; // 最小列寬
        const padding = 30; // 額外的內邊距
        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或者其他適當?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)
 })
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容