这里可对内容为文本的列进行自适应列宽
以下为 工具方法
/**
* 使用span标签包裹内容,然后计算span的宽度 width: px
* @param valArr
*/
function getTextWidth(str) {
let width = 0;
// 创建 span 标签对象 并对该标签 插入 文本属性 及 类名
let html = document.createElement('span');
html.innerText = str;
html.className = 'getTextWidth';
// 获取 body 元素 并插入 前面创建的 span 标签
document.querySelector('body').appendChild(html);
// 获取当前 span 标签 的类名的 偏移宽度,这个宽度与页面所显示宽度一致
width = document.querySelector('.getTextWidth').offsetWidth;
document.querySelector('.getTextWidth').remove();
return width;
}
/**
* 遍历列的所有内容,获取最宽一列的宽度
* @param arr
*/
function getMaxLength(arr) {
return arr.reduce((acc, item) => {
if (item) {
let calcLen = getTextWidth(item)
if (acc < calcLen) {
acc = calcLen
}
}
return acc
}, 0)
}
完成了工具方法的实现,下面对el-table的数据源进行处理
tableData: {
handler(oldVal, newVal) {
this.tableData = oldVal
const _this = this
_this.tableData = _this.tableData.map(function(value) {
const arr = oldVal.map(x => x[value.prop]) // 获取每一列的所有数据
arr.push(value.label) // 把每列的表头也加进去算
value.width = getMaxLength(arr) + 20 // 每列内容最大的宽度 + 表格的内间距(依据实际情况而定)
return value
})
},
deep: true,
immediate: true
},
页面el-table渲染dom结构
<el-table-column v-for="(item,index) in tableData" :key="Math.random()" :prop="item.prop" :label="item.label" :width="item.width"></el-table-column>
这里要求自定义一个 列表结构 ,可在工具类自定义 也可在 data 定义
tableData: [{
label: '姓名',
prop: 'name',
width: "60"
}
],