el-table-column 自适应列宽

1、src/utils下新建columnWidth.js文件

export function flexColumnWidth(str, tableData) {
    // 确保 str 和 tableData 是字符串和数组
    str = str + '';
    if (!tableData || !Array.isArray(tableData) || tableData.length === 0) {
        return '80px';
    }
    if (!str || str.length === 0) {
        return '80px';
    }

    // 获取该列中最长的数据(内容)
    let index = 0;
    for (let i = 0; i < tableData.length; i++) {
        if (tableData[i][str] === null) {
            continue;
        }
        const now_temp = tableData[i][str] + '';
        const max_temp = (tableData[index][str] || '').toString();
        if (now_temp.length > max_temp.length) {
            index = i;
        }
    }

    const columnContent = tableData[index][str];
    if (!columnContent) {
        return '80px';
    } else {
        // 以下分配的单位长度可根据实际需求进行调整
        let flexWidth = 0;
        for (const char of columnContent) {
            if ((char >= 'A' && char <= 'Z') || (char >= 'a' && char <= 'z')) {
                flexWidth += 8;
            } else if (char >= '\u4e00' && char <= '\u9fa5') {
                flexWidth += 12;
            } else {
                flexWidth += 8;
            }
        }
        // 确保最小宽度为 80px
        flexWidth = Math.max(flexWidth, 80);
        // 添加额外的宽度
        flexWidth += 30;
        return flexWidth + 'px';
    }
}

2、main.js中配置方法

import { flexColumnWidth } from '@/utils/columnWidth.js'

Vue.prototype.flexColumnWidth = flexColumnWidth

3、使用方法

<template>
    <div>
        <el-table v-loading="tableLoading" border :data="tableData" :cell-style="cellStyle">
            <el-table-column label="公司" align="center" prop="companies"
                :width="flexColumnWidth('companies', tableData)" />
        </el-table>
    </div>
</template>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值