由于表头和列是分开渲染的,通过el-table 设置fit属性,只能撑开表头,但是没有办法根据列的内容去适应宽度。网上找了一些使用根据表格内容计算表头宽度的文章,记个笔记。

代码逻辑是通过vue 的watch 监控表格的数据data,计算每列的内容和表头的最大宽度,计算的时候把表格内容使用span标签包裹,然后计算span标签的宽度width:px,然后再加上表格的内边距,

就得到了列的最大宽度.

<el-table :data="tableData"  v-loading="loading" style="width: 100%;" >
<el-table-column v-for="(column, index) in columns"
:key="index"
:label="column.label"
:width="column.width" <!-- 设置宽度 -->
show-overflow-tooltip>
<template slot-scope="scope">
{{ scope.row[column.prop] }}
</template>
</el-table-column>
</el-table>

<script>


export default {
data() {
return {
columns: [ // 默认表头 Default header
{
label: '任务年月',
prop: 'nianyue',
},
{
label: '创建部门',
prop: 'bumenbmmc',
},
],
tableData: [] //表格数据
};
},

methods: {
/**
* 遍历列的所有内容,获取最宽一列的宽度
* @param arr
*/
getMaxLength (arr) {
return arr.reduce((acc, item) => {
if (item) {
let calcLen = this.getTextWidth(item)
if (acc < calcLen) {
acc = calcLen
}
}
return acc
}, 0)
},

/**
* 使用span标签包裹内容,然后计算span的宽度 width: px
* @param valArr
*/
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;
},

/**
* @description 计算列表列宽(把内容撑开)
* @param {Array} columns 列的数组
* @param {Array} tableArr 列表的数组
* */
calcColumnsWidth(columns, tableArr) {
columns.forEach((item) => {
const prr = tableArr.map((x) => x[item.prop]);
// item.width = getMaxLength(arr) + 30; // 每列内容最大的宽度 + 表格的内间距(依据实际情况而定)
if (this.getMaxLength(arr) === 0) {
Vue.prototype.$set(item, 'width', (getMaxLength(arr) + 60));
} else if (this.getMaxLength(arr) < 10) {
Vue.prototype.$set(item, 'width', (getMaxLength(arr) + 60));
} else if (this.getMaxLength(arr) < 40) {
Vue.prototype.$set(item, 'width', (getMaxLength(arr) + 70));
} else if (this.getMaxLength(arr) < 100) {
Vue.prototype.$set(item, 'width', (getMaxLength(arr) + 50));
} else if (this.getMaxLength(arr) < 350) {
Vue.prototype.$set(item, 'width', (getMaxLength(arr)));
} else {
Vue.prototype.$set(item, 'width', 350);
}
// console.log(getMaxLength(arr));
// Vue.prototype.$set(item, 'width', (getMaxLength(arr) + 30));
arr.push(item.label); // 把每列的表头也加进去算
});
return columns;
}
},

watch: {
/**
* 监控表格的数据data,自动设置表格宽度
* @param valArr
*/
tableData: {
handler(valArr) {
const columns = this.calcColumnsWidth(this.columns, valArr);
this.columns = columns;
},
deep: true,
},
}
}
</script>

参考:

​​vue el-table 自适应表格内容宽度​​