公司最近有一个需求是:在中英文国际化情况下,列表的表头要自适应,不能出现换行的情况.
一开始我的做法是设置min-width,但是有的字段中文情况下是显示正常的,但是英文情况下会出现换行;此时如果根据英文长度去设置宽度,但是中文情况下列表的宽度又太宽了,不太美观;所以封装了一个方法,根据表头label自身的宽度自适应
先自定义一个js文件,然后在main.js中引入,然后全局就可以引用了
const commonJS = {
renderHeader(h, { column, $index }) {
let width = 0
// 新建一个 span
let span = document.createElement('span');
// 设置表头名称
span.innerText = column.label;
// 设置表头class
span.className = 'getTextWidth'
// 临时插入 document
document.querySelector('body').appendChild(span)
// 获取span标签的宽度
width = document.querySelector('.getTextWidth').offsetWidth
// 重点:获取span最小宽度,设置当前列,注意这里加了20,字段较多时还是有挤压,且渲染后的div内左右padding都是10,所以+20.如果有排序按钮要记得再加上24,排序按钮的宽度是24(可能还有边距/边框等值,需要根据实际情况加上)
column.minWidth = width + 50;
// 移除 document 中临时的 span
document.querySelector('.getTextWidth').remove()
return h('span', column.label);
},
}
export default commonJS;
在el-table中引用:render-header="utils.renderHeader"
<el-table :data="tableData" :row-key="getRowKeys" ref="multipleTable" @selection-change="handleSelectionChange" @select="select" @select-all="selectAll" v-loading="loading" size="mini" @sort-change="sortChange" max-height="500" border stripe>
<el-table-column type="selection" width="55" fixed></el-table-column>
<template v-for="(item,index) in colLists">
<el-table-column show-overflow-tooltip :key="`col_${index}`" sortable="custom" :prop="item.prop" :label='item.label' v-if="item.isTrue" :render-header="utils.renderHeader"></el-table-column>
</template>
</el-table>