表格列宽自适应

代码部分

<el-table border :data="tableData" fit style="width: 100%">
      <el-table-column label="日期" :width="flexColumnWidth('string',tableData)">
        <template slot-scope="scope">
          <span>{{ scope.row.string }}</span>
        </template>
      </el-table-column>
  </el-table>

js部分

flexColumnWidth(str, arr1, flag = 'max') {
			if (!arr1 || !arr1.length) return;
			if (!str || typeof str !== 'string') return;

			let columnContent = '';
			if (flag === 'equal') {
				for (let i = 0; i < arr1.length; i++) {
					if (arr1[i] && arr1[i] && arr1[i][str] !== undefined && arr1[i][str] !== null) {
						columnContent = arr1[i][str];
						break;
					}
				}
			} else {
				let maxLength = 0;
				for (let i = 0; i < arr1.length; i++) {
					if (arr1[i] && arr1[i] && arr1[i][str] !== undefined && arr1[i][str] !== null) {
						const length = arr1[i][str]?.toString()?.length ?? 0;
						if (length > maxLength) {
							maxLength = length;
							columnContent = arr1[i][str];
							
						}
					}
				}
			}

			// 计算宽度
			const calculateWidth = (text) => {
				let width = 0;
				if (text !== null && text !== undefined) {
					for (const char of text.toString()) {
						if (char.match(/[A-Za-z]/)) {
							width += 9; // 英文字符
						} else if (char.match(/[\u4e00-\u9fa5]/)) {
							width += 16; // 中文字符
						} else if (char.match(/[0-9]/)) {
							width += 7; // 数字字符
						} else if (char === ' ') {
							width += 8; // 空格
						} else {
							width += 10; // 其他字符
						}
					}
				}
				if (width > 480) {
					return 480; // 设置最大宽度
				}
				// else if (width < 200) {
				// 	return Math.max(200, 200); // 设置最大宽度
				// }
				return Math.max(width, 60); // 设置最小宽度
			};
			if (columnContent.length && columnContent[0].url) {//图片视频默认宽度
				return 70 * columnContent.length + 'px'
			}

			
			return calculateWidth(columnContent) + 32 + 'px';
		}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值