以下代码是vue3写的:
1.根据表头设置动态宽
<el-table-column
v-for="item,index in data.headerList" :key="index" :width="item.width>=160 ? item.width : '160'">
<template #header>
<view>
{{item.name}}
</view>
</template>
<template #="scope">
</template>
</el-table-column>
//data.headerList是表头数据
onMounted(() => {
data.headerList.forEach(item => {
item.width = renderHeaderTable(item)
});
});
const renderHeaderTable = (item) => {
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
context.font = "16px Arial";
const metrics = context.measureText(item.dataTypeName);
return metrics.width + 24;
}
2.根据列单元格内容动态设置最长宽度
<el-table-column :width="data.width">
<template #default="scope">
<span class="tableName">
{{ scope.row.XXX}}
</span>
</template>
</el-table-column>
onMounted(() => {
//等表格加载完以后,这里用nextTick都没用(需要去了解下他们两之间的区别)
setTimeout(() => {
widthHandle()
}, 1);
});
const widthHandle=()=>{
let width=140
const opts = document.getElementsByClassName("tableName");
let widthArr = [];
Array.prototype.forEach.call(opts, function (item) {
const rect = item.getBoundingClientRect();
const textWidth = rect.width;
widthArr.push(textWidth);
});
if (widthArr.length > 0) {
width = Math.max(...widthArr) + 40;
}
data.width=width
}