代码部分
<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';
}