el-table表头自适应表格内容宽度方法
一、问题引入
表格内容不一致,需要自适应宽度展示
二、方案一
场景:直接根据表格内容,动态设置宽度,适用于不同权限,内容减少

代码如下
<el-table-column label="操作" class-name="handle-column" :width="autoWidth" align="left" fixed="right">
</el-table-column>
获取列表数据的时候,自适应调整宽度
getTableList(data) { this.tableList = data; this.$nextTick(() => { const tds = document.querySelectorAll('td.handle-column>.cell') if (tds && tds.length) { this.autoWidth = Math.max(...[...tds].map(v => v.offsetWidth)) this.$refs.tableBox1.doLayout() } }); },
三、方案二
场景:直接根据内容字符串长度,动态设置宽度。需根据不同类型字符串字符,设置不同宽度。
定义字符宽度并计算每行内容最大宽度
/** * @description: 自适应表格列宽 * @param {*} prop 列字段名(字符串) * @param {*} label 表头名(字符串) * @param {*} tableData tableData 表格数据源(变量) * @param {*} flag 'max'或'equal',默认为'max' * @param {*} flag flag为'max'则设置列宽适配该列中最长的内容,flag为'equal'则设置列宽适配该列中第一行内容的长度 * @return {*} */ function flexColumnWidth(prop, label, tableData, flag = 'max') { let columnWidth = 0 let minWidth = 80 if (label && label.length) { minWidth = label.split('').reduce((pre, cur) => { pre += getChrtSize(cur) return pre; }, 0) } if (tableData && tableData.length && prop && prop.length) { if (flag === 'equal') { // 获取该列中第一个不为空的数据(内容) const columnContent = tableData.find(v => v[prop]) || '' columnWidth = columnContent.split('').reduce((pre, cur) => { pre += getChrtSize(cur) return pre; }, 0) } else { // 获取该列中最长的数据(内容) const contentList = tableData.map(v => { if (v[prop]) { const length = v[prop].split('').reduce((pre, cur) => { pre += getChrtSize(cur) return pre; }, 0) return length; } return 0; }) console.log('contentList', contentList); columnWidth = Math.max(...contentList) } } console.log('label', label, minWidth, prop, columnWidth, tableData); const width = (columnWidth < minWidth) ? minWidth : columnWidth return ((width + 20) + 'px'); } function getChrtSize(char) { if (char >= 'a' && char <= 'z') { // 小写英文字符,分配8个单位宽度 return 8 } else if (char >= 'A' && char <= 'Z') { // 小写英文字符,分配12个单位宽度 return 12 } else if (char >= '\u4e00' && char <= '\u9fa5') { // 中文字符,分配15个单位宽度 return 15 } else if ((char > 0 && char < 9) || char == '0') { // 数字字符,分配8个单位宽度 return 10 } else { // 其他种类字符,分配10个单位宽度 return 8 } }
页面上使用
<el-table-column resizable v-for="(v, i) in selectFieldDetail" :key="i" :label="v.chnField" :prop="v.field" :width="$flexColumnWidth(v.field, v.chnField, detailData)" :show-overflow-tooltip="true"> </el-table-column>

浙公网安备 33010602011771号