eltable自适应列宽

222 阅读1分钟

原理:计算宽度复制:width

image.png

1.创建tableUtils.js文件

image.png

/**
 * 使用span标签包裹内容,然后计算span的宽度 width: px
 * @param valArr
 */
function getTextWidth (str) {
  let width = 0
  const html = document.createElement('span')
  html.innerText = str
  html.className = 'getTextWidth'
  document.querySelector('body').appendChild(html)
  width = document.querySelector('.getTextWidth').offsetWidth
  document.querySelector('.getTextWidth').remove()
  return width
}

/**
 * 遍历列的所有内容,获取最宽一列的宽度
 * @param arr
 */
function getMaxLength (arr) {
  return arr.reduce((acc, item) => {
  if (item) {
    const calcLen = getTextWidth(item)
    if (acc < calcLen) {
      acc = calcLen
    }
  }
    return acc
  }, 0)
}

/**
 * el-table-column 自适应列宽
 */
const autoColumnWidth = function(label, prop, table_data) {
  // 1.获取该列的所有数据
  // console.log('label :>> ', label);
  // console.log('prop :>> ', prop);
  const arr = table_data.map(x => x[prop])
  arr.push(label) // 把每列的表头也加进去算
  // console.log('arr :>> ', arr);
  // 2.计算每列内容最大的宽度 + 表格的内间距(依据实际情况而定)
  return (getMaxLength(arr) + 25) + 'px'
}

export {
  autoColumnWidth
} 

2.在需要的页面引入

image.png

注意,要在methods中重新定义一下方法

image.png

3.在el-table-column中的width使用函数

image.png