Vue+element組合el-table-column表頭寬度自定義


[本文出自天外歸雲的博客園]

需求

1. 某列表頭文字內容過長,要對每列表頭自定義寬度

2. 表格row的每一column文字不換行,超過列寬則省略,mouseover有提示

3. 對於label做濾值處理

實現

Vue文件主要代碼如下:

<template>
  <el-row>
    <el-col :span="24">
      <template>
        <el-table :data="tableData">
          <!--設置show-overflow-tooltip為true使row中的文字有省略提示-->
          <el-table-column :width="flexColumnWidth(column)" :show-overflow-tooltip="true" v-for="column in tableData.columns" :key="column" :label="customLabel(column)" :prop="column">
          </el-table-column>
        </el-table>
      </template>
    </el-col>
  </el-row>
</template>
<script>
export default{
  data() {
    return {
      tableData : {
        'columns': ['測試列頭含有中文且長度過長的情況','test the column th is so long in English','c3'],
        'rows': [
          {
            '測試列頭含有中文且長度過長的情況': 'v1',
            'test the column th is so long in English': 'v2',
            'c3': 'v3'
          },
        ]
      },
      methods: {
        // 自定義label內容過濾器
        customLabel(str) {
          let ret = ''
          for (const char of str) {
            // 例:濾掉空格
            if (char !== ' '){
              ret += char
            }
          }
          return ret
        },
        // 自定義表頭列寬
        flexColumnWidth(str) {
          let flexWidth = 0
          for (const char of str) {
            if ((char >= 'A' && char <= 'Z') || (char >= 'a' && char <= 'z')) {
              // 如果是英文字符,為字符分配8個單位寬度
              flexWidth += 8
            } else if (char >= '\u4e00' && char <= '\u9fa5') {
              // 如果是中文字符,為字符分配20個單位寬度
              flexWidth += 20
            } else {
              // 其他種類字符,為字符分配5個單位寬度
              flexWidth += 5
            }
          }
          if (flexWidth < 50) {
            // 設置最小寬度
            flexWidth = 200
          }
          if (flexWidth > 250) {
            // 設置最大寬度
            flexWidth = 250
          }
          return flexWidth + 'px'
        },
      }
    }
  }
})

 


免責聲明!

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



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