百度了各位大佬各种方法,(npm下载,:width,:render-header,css处理)本人喜欢以最小的改动实现需求,我的项目里有20多个表格
最终选择:width方法
<el-table v-loading="loading" :data="ownerList" @selection-change="handleSelectionChange" >
<el-table-column type="selection" width="55" align="center" />
<el-table-column label="主键id" align="center" prop="id" />
<el-table-column label="货权主编码" align="center" prop="cargoOwnerCode" :width="flexWidth('cargoOwnerCode',ownerList,'货权主编码')"/>
<!-- :width="flexWidth('cargoOwnerCode',ownerList,'货权主编码')" -->
<!-- :render-header="renderHeader" -->
<el-table-column label="货权主名称" align="center" prop="cargoOwnerName" :width="flexWidth('cargoOwnerName',ownerList)" />
<el-table-column label="状态" align="center" prop="status">
<template slot-scope="scope">
<dict-tag :options="dict.type.wms_status" :value="scope.row.status"/>
</template>
</el-table-column>
</el-table>
methods: {
flexWidth(prop, tableData, title, num = 0) {
// 1参数'prop'
// 2参数 tableData
// 3参数 'lable' 可不传
if (tableData.length === 0 ) {//表格没数据不做处理
return;
}
let flexWidth = 0;//初始化表格列宽
let columnContent = '';//占位最宽的内容
let canvas = document.createElement("canvas");
let context = canvas.getContext("2d");
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 || '留四个字'
}
}
// 计算最宽内容的列宽
let width = context.measureText(columnContent);
flexWidth = width.width + 40 + num
return flexWidth + 'px';
}
}
最终效果图
麻烦的点就是 要给每一个长列都加上:width