el-table表格列根据每页内容自动计算宽度

image.png
image.png
 <el-table-column
        label="本次核销金额"
        align="right"
        prop="writeOffAmount"
        :min-width="flexColumnWidth('本次核销金额', 'writeOffAmount', unverifiedTableData)"
       />

   <el-table-column
        v-for="(col, index) in tableColumns.activeFields"
        :key="index"
        :prop="col.prop"
        :label="col.label"
        :width="col.width"
        :min-width="flexColumnWidth(col.label, col.prop, msgList) "
        :show-overflow-tooltip="col.showOverflowTooltip !== 'hidden'"
        :align="col.align"
        :sortable="col.sortable">
import { flexColumnWidth } from 'flexColumnWidth.js';
// 函数用于计算给定字符串在页面上的显示宽度,并放大一定比例以适应布局需求
export function getTextWidth(str) {
  let width = 0;
  // 创建一个 span 元素用于测量文本宽度
  const html = document.createElement('span');
  html.innerText = str;
  html.className = 'getTextWidth';
  // 将 span 元素添加到 body 中以便获取其宽度
  document.querySelector('body').appendChild(html);
  // 获取 span 的宽度并放大 20%
  width = document.querySelector('.getTextWidth').offsetWidth * 1.2;
  // 移除 span 元素
  document.querySelector('.getTextWidth').remove();
  // 返回计算后的宽度
  return width;
}

// 动态计算列宽
export function flexColumnWidth(label, prop, data, padding = 48) {
  // 从数据集中提取指定属性的值
  const arr = data.map((x) => x[prop]);
  // 添加标签作为最后一项进行比较
  arr.push(label);
  // 计算所有项的最大宽度
  const maxWidth = arr.reduce((acc, item) => {
    if (item) {
      // 调用 getTextWidth 函数获取每个项的显示宽度
      const width = getTextWidth(item);
      // 更新最大宽度
      acc = Math.max(acc, width);
    }
    // 返回当前最大宽度
    return acc;
  }, 0);
  // 返回最大宽度加上额外的内间距
  return maxWidth + padding + 'px';
}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容