目的:让列根据内容自适应
<el-table
:data="selectList"
border
style="width: 100%;"
v-loading="loading"
height="740"
>
<el-table-column
v-for="item in tableColumn"
:key="item.index"
:label="item.label"
:prop="item.prop"
align="center"
:width="flexColumnWidth(item.prop, selectList)"
>
<template slot-scope="scope">
{{ scope.row[item.prop] }}
</template>
</el-table-column>
// 计算每列列宽自适应表格列宽
flexColumnWidth(str, tableData, flag = "max") {
// str为该列的字段名
// flag为可选值,可不传该参数,传参时可选'max'或'equal',默认为'max'
str = str + "";
let columnContent = "";
if (
!tableData ||
!tableData.length ||
tableData.length === 0 ||
tableData === undefined
) {
return;
}
if (!str || !str.length || str.length === 0 || str === undefined) {
return;
}
if (flag === "equal") {
// 获取该列中第一个不为空的数据(内容)
for (let i = 0; i < tableData.length; i++) {
if (tableData[i][str].length > 0) {
columnContent = tableData[i][str];
break;
}
}
} else {
// 获取该列中最长的数据(内容)
let index = 0;
for (let i = 0; i < tableData.length; i++) {
if (tableData[i][str] == null) {
continue; //因为我数据中有的是null,所以用的continue,没有用return
}
const now_temp = tableData[i][str] + "";
const max_temp = tableData[index][str] + "";
if (now_temp.length > max_temp.length) {
index = i;
}
}
columnContent = tableData[index][str];
}
// 以下分配的单位长度可根据实际需求进行调整
let flexWidth = 0;
if (columnContent != null) {
// let flexWidth = 0;
for (const char of columnContent) {
if ((char >= "A" && char <= "Z") || (char >= "a" && char <= "z")) {
// 如果是英文字符,为字符分配8个单位宽度
flexWidth += 8;
} else if (char >= "\u4e00" && char <= "\u9fa5") {
// 如果是中文字符,为字符分配16个单位宽度
flexWidth += 16;
} else {
// 其他种类字符,为字符分配8个单位宽度
flexWidth += 8;
}
}
}
if (flexWidth < 80) {
// 设置最小宽度
flexWidth = 80;
}
if (flexWidth > 600) {
// 设置最大宽度
flexWidth = 600;
}
return flexWidth + "px";
}