今天发现,element表格控件中给的fit属性不生效,于是找到了一些可以自适应列宽的方法
1.根据内容
// 表格内容设置
<el-table-column prop="roomid" label="锅炉房ddfgdfgd电视柜苟富贵1121356465(KS)" :render-header="renderHeader"></el-table-column>
// 具体方法
renderHeader(h, { column, $index }) {
let realWidth = 0;
let title = ''
let unit = ''
let span = document.createElement('span');
// 这里加的样式为表头的样式,用于精准计算需要的宽度
span.style.fontSize = '14px'
span.style.fontWeight = '700'
// 标题,用于计算列宽
let span1 = document.createElement('span');
span1.style.fontSize = '14px'
span1.style.fontWeight = '700'
// 单位,用于计算列宽
let span2 = document.createElement('span');
span2.style.fontSize = '14px'
span2.style.fontWeight = '700'
if( column.label.indexOf("(") > 0 ) {
title = column.label.substring(0, column.label.indexOf("("))
unit = column.label.substring(column.label.indexOf("("))
} else if ( column.label.indexOf("(") > 0 ) {
title = column.label.substring(0, column.label.indexOf("("))
unit = column.label.substring(column.label.indexOf("("))
} else {
title = column.label
}
span1.innerText = title
span2.innerText = unit
document.body.appendChild(span1);
document.body.appendChild(span2);
span.innerText = span1.getBoundingClientRect().width > span2.getBoundingClientRect().width ? title : unit;
document.body.appendChild(span);
realWidth = span.getBoundingClientRect().width;
column.minWidth = realWidth + 22; // 可能还有边距/边框等值,需要根据实际情况加上
document.body.removeChild(span);
document.body.removeChild(span1);
document.body.removeChild(span2);
// 其中 20 为左右边距 2 为 左右边框宽度
return h('div', null, [h('div', title), h('div', unit)])
},
2.动态宽度方法,并实现单位换行
效果图
代码
// html
<el-table-column :width="renderHeight('锅炉房(m³)')" prop="roomid" label="锅炉房(m³)" scoped-slot>
<template slot="header" slot-scope="scope">
<span>锅炉房</span><br><span>(m³)</span>
</template>
</el-table-column>
// js
renderHeight(label) {
let realWidth = 0;
let title = ''
let unit = ''
let span = document.createElement('span');
// 这里加的样式为表头的样式,用于精准计算需要的宽度
span.style.fontSize = '14px'
span.style.fontWeight = '700'
// 标题,用于计算列宽
let span1 = document.createElement('span');
span1.style.fontSize = '14px'
span1.style.fontWeight = '700'
// 单位,用于计算列宽
let span2 = document.createElement('span');
span2.style.fontSize = '14px'
span2.style.fontWeight = '700'
if( label.indexOf("(") > 0 ) {
title = label.substring(0, label.indexOf("("))
unit = label.substring(label.indexOf("("))
} else if ( label.indexOf("(") > 0 ) {
title = label.substring(0, label.indexOf("("))
unit = label.substring(label.indexOf("("))
} else {
title = label
}
span1.innerText = title
span2.innerText = unit
document.body.appendChild(span1);
document.body.appendChild(span2);
span.innerText = span1.getBoundingClientRect().width > span2.getBoundingClientRect().width ? title : unit;
document.body.appendChild(span);
realWidth = span.getBoundingClientRect().width;
document.body.removeChild(span);
document.body.removeChild(span1);
document.body.removeChild(span2);
// 其中 20 为左右边距 2 为 左右边框宽度
return realWidth + 20 + 2
},