参考:https://www.cnblogs.com/huangxiaoxue/p/12034326.html
<el-table
stripe
empty-text="暂无数据"
tooltip-effect="dark"
:fit="true"
:data="list"
class="hf-table-mgt__table-detail"
header-row-class-name="u-table-tit"
row-class-name="u-hover">
<el-table-column
v-for="(option, index) in tableOptions"
:key="index"
:width="option.width"
:label="option.columnComment"
:prop="option.columnName">
</el-table-column>
</el-table>
watch: {
list(valArr) {
this.tableOptions = this.tableOptions.map((value) => {
const arr = valArr.map(x => x[value.columnName]) // 获取每一列的所有数据
arr.push(value.columnComment) // 把每列的表头也加进去算
value.width = this.getMaxLength(arr) + 20 // 每列内容最大的宽度 + 表格的内间距(依据实际情况而定)
return value
})
// console.log('watch', this.tableOptions)
}
},
methods: {
// 遍历列的所有内容,获取最宽一列的宽度
getMaxLength (arr) {
return arr.reduce((acc, item) => {
if (item) {
let calcLen = this.getTextWidth(item)
if (acc < calcLen) {
acc = calcLen
}
}
return acc
}, 0)
},
getTextWidth(str) {
let width = 0;
let html = document.createElement('span');
html.innerText = str;
html.className = 'getTextWidth';
document.querySelector('body').appendChild(html);
width = document.querySelector('.getTextWidth').offsetWidth;
document.querySelector('.getTextWidth').remove();
return width;
},
}
网友评论