el-table表格内容自适应撑开

<el-table :key="key" :data="data"  v-loading="loading" style="width: 100%;" >
      <el-table-column v-for="item in formThead"
                   :key="item.prop"
                   :label="item.label"
                   :width="item.width"  <!-- 设置宽度 -->
                   show-overflow-tooltip>
        <template slot-scope="scope">
          {{ scope.row[fruit.prop] }}
        </template>
    </el-table-column>
</el-table>

<script>

let colList = [

{ prop: "fy", label: "费用收取方式" },

{ prop: "product", label: "产品大类" },

{ prop: "tc", label: "投产策略" },

{ prop: "zkq", label: "子客群" },

{ prop: "custExistenceType", label: "首续贷" },

{ prop: "repayType", label: "还款方式" },

{ prop: "loanType", label: "抵押类型" },

{ prop: "irr", label: "IRR" },

{ prop: "beginTerm", label: "开始期次" },

{ prop: "endTerm", label: "结束期次" },

]


export default {
    data() {
        return {
            colList: colList, // 默认表头 Default header
            list: []
        };
    },

    methods: {
        * 遍历列的所有内容,获取最宽一列的宽度
        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
        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,自动设置表格宽度
        data(valArr) {
            const _this = this
            this.formThead = colList.map(function (value) {
                const arr = valArr.map(x => x[value.prop])  // 获取每一列的所有数据
                arr.push(value.label)  // 把每列的表头也加进去算
                value.width = _this.getMaxLength(arr) + 20 // 每列内容最大的宽度 + 表格的内间距(依据实际情况而定)
                return value
            })
        }
    }
}
</script>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值