---
title: "vue el-table 自适应(转)"
author: "cuityang"
date: "2022-02-07T16:32:43Z"
tags: []
categories: ["Web前端"]
slug: "vue-el-table"
draft: false
lastmod: "2022-02-07T16:32:43Z"
id: 2524316
url: "https://cuityang.iteye.com/blog/2524316"
---

由于表头和列是分开渲染的，通过el-table 设置fit属性，只能撑开表头，但是没有办法根据列的内容去适应宽度。网上找了一些使用根据表格内容计算表头宽度的文章，记个笔记。

代码逻辑是通过vue  的watch 监控表格的数据data，计算每列的内容和表头的最大宽度，计算的时候把表格内容使用span标签包裹，然后计算span标签的宽度width：px，然后再加上表格的内边距，

就得到了列的最大宽度.

<el-table :key="key" :data="data"  v-loading="loading" style="width: 100%;" >
      <el-table-column v-for="fruit in formThead"
                   :key="fruit.prop"
                   :label="fruit.label"
                   :width="fruit.width"  <!-- 设置宽度 -->
                   show-overflow-tooltip>
        <template slot-scope="scope">
          {{ scope.row }}
        </template>
    </el-table-column>
</el-table>

<script>
const fields = 


export default {
    data() {
        return {
            url: "asset",
            key: 1, // table key
            formThead: fields, // 默认表头 Default header
            data: 
        };
    },

    methods: {
        /**
        * 遍历列的所有内容，获取最宽一列的宽度
        * @param arr
        */
        getMaxLength (arr) {
          return arr.reduce((acc, item) => {
            if (item) {
              let calcLen = this.getTextWidth(item)
              if (acc < calcLen) {
                acc = calcLen
              }
            }
            return acc
          }, 0)
        },
        /**
         * 使用span标签包裹内容，然后计算span的宽度 width： px
         * @param valArr
         */
        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;
        }
    },

    watch: {
        /**
         * 监控表格的数据data，自动设置表格宽度
         * @param valArr
         */
        data(valArr) {
            const _this = this
            this.formThead = fields.map(function (value) {
                const arr = valArr.map(x => x)  // 获取每一列的所有数据
                arr.push(value.label)  // 把每列的表头也加进去算
                value.width = _this.getMaxLength(arr) + 20 // 每列内容最大的宽度 + 表格的内间距(依据实际情况而定)
                return value
            })
        }
    }
}
</script>


https://www.cnblogs.com/huangxiaoxue/p/12034326.html