/**
* dynamicCalculationWidth
* @param string | number prop 每列的prop 可传''
* @param array tableData 表格数据
* @param string | number title 标题长内容短的,传标题 可不传
* @param number num 列中有标签等加的富余量
* @returns 每列的宽度
* 注:prop,title有一个必传
*/
export const dynamicCalculationWidth = (prop2: string, tableData: string | any[], title2: string, num = 0) => {
const prop = prop2.replace('\n', '');
const title = title2.split('\n')[0];
if (tableData.length === 0) {
// 表格没数据不做处理
return 'auto';
}
let flexWidth = 0; // 初始化表格列宽
let columnContent = ''; // 占位最宽的内容
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d') as CanvasRenderingContext2D;
context.font = '14px Microsoft YaHei';
if (prop === '' && title) {
// 标题长内容少的,取标题的值,
columnContent = title;
} else {
// 获取该列中占位最宽的内容
let index = 0;
for (let i = 0; i < tableData.length; i++) {
const now_temp = tableData[i][prop] + '';
const max_temp = tableData[index][prop] + '';
const now_temp_w = context.measureText(now_temp).width;
const max_temp_w = context.measureText(max_temp).width;
if (now_temp_w > max_temp_w) {
index = i;
}
}
columnContent = tableData[index][prop];
// 比较占位最宽的值跟标题、标题为空的留出四个位置
const column_w = context.measureText(columnContent).width;
const title_w = context.measureText(title).width;
if (column_w < title_w) {
columnContent = title || '占位符呀';
}
}
// 计算最宽内容的列宽
const width = context.measureText(columnContent);
flexWidth = width.width + 40 + num;
return flexWidth + 'px';
};
el-table min-width根据字段内容设置列宽
最新推荐文章于 2024-07-03 21:10:53 发布