美文网首页
el-table 自适应表格内容宽度

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

作者: gem_Y | 来源:发表于2020-01-20 14:30 被阅读0次

参考: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;
    },
}

相关文章

网友评论

      本文标题:el-table 自适应表格内容宽度

      本文链接:https://www.haomeiwen.com/subject/whujzctx.html