el-table 自适应表格内容宽度

参考:https://www.cnblogs.com/huangxiaoxue/p/12034326.html

      <el-table
        stripe
        empty-text="暂无数据"
        tooltip-effect="dark"
        :fit="true"
        :data="list"
        class="hf-table-mgt__table-detail"
        header-row-class-name="u-table-tit"
        row-class-name="u-hover">
        <el-table-column
          v-for="(option, index) in tableOptions"
          :key="index"
          :width="option.width"
          :label="option.columnComment"
          :prop="option.columnName">
        </el-table-column>
      </el-table>
  watch: {
    list(valArr) {
      this.tableOptions = this.tableOptions.map((value) => {
        const arr = valArr.map(x => x[value.columnName])  // 获取每一列的所有数据
        arr.push(value.columnComment)  // 把每列的表头也加进去算
        value.width = this.getMaxLength(arr) + 20 // 每列内容最大的宽度 + 表格的内间距(依据实际情况而定)
        return value
      })
      // console.log('watch', this.tableOptions)
    }
  },
  methods: {

    // 遍历列的所有内容,获取最宽一列的宽度
    getMaxLength (arr) {
      return arr.reduce((acc, item) => {
        if (item) {
          let calcLen = this.getTextWidth(item)
          if (acc < calcLen) {
            acc = calcLen
          }
        }
        return acc
      }, 0)
    },
    getTextWidth(str) {
      let width = 0;
      let html = document.createElement('span');
      html.innerText = str;
      html.className = 'getTextWidth';
      document.querySelector('body').appendChild(html);
      width = document.querySelector('.getTextWidth').offsetWidth;
      document.querySelector('.getTextWidth').remove();
      return width;
    },
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 今天我遇见了迎亲队伍,今天我跟一个小人无赖贱人吵了一架。 虽然我穿了踩小人袜子可依旧有小人。 今天下乡吃了心心念的...
    风吹乱我的发丝阅读 1,180评论 0 0
  • 在知乎搜索的时候发现一个新词聚合搜索 由此发现了3个网站 筛选了每个网站最好的一点 你看看能不能做到一款拓展或者网...
    千千万万道不明阅读 9,001评论 5 3
  • 如果一个人从来不打开自己的心,不和外界交流,不给予别人东西,不把自己的心腾空,别人就是想给你,无论是合作机会,还...
    花间精凌阅读 1,531评论 2 2
  • 一 我曾经看到过这样一段文字:我听见有些东西在我心的忧闷后面萧萧作响,我不能看见它们。亦如我再寻不见你的踪迹。风往...
    叶叙呢阅读 3,610评论 0 4
  • 他是一个孤儿,用谎言来描绘自己的生活,在与人交谈的她扮演着小丑,也只能够这样才能让人们不去过分注意她,变得不显眼,...
    ZacPason阅读 3,325评论 9 1

友情链接更多精彩内容