element el-table表格内容宽度自适应,不换行,不隐藏

2024.2.27今天我学习了如何用el-table实现表格宽度的自适应,当我们动态渲染表格数据的时候,有时候因为内容太多会出现挤压换行的效果:

我们需要根据内容的最大长度设置动态的宽度,这边我在utils里面封装了一个js:

javascript 复制代码
//el-table表格内容宽度自适应
const content_width_adaptation_js = {
  flexColumnWidth(label, prop, table_data) {
    //label表格列表
    //prop列表对应的数据
    //table_data表格数据
    const arr = table_data.map(item => item[prop])
    arr.push(label)
    // 自动撑开表格内容最大宽度
    function getMaxLength(arr) {
      return arr.reduce((acc, item) => {
        if (item) {
          const calcLen = getTextWidth(item)
          if (acc < calcLen) {
            acc = calcLen
          }
        }
        return acc
      }, 0)
    }
    // 自动撑开表格内容最大宽度
    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
    }
    return (getMaxLength(arr) + 40) + 'px'
  },
}
export default content_width_adaptation_js

然后在main.js中引入:

javascript 复制代码
import elTableAdaptationWidth from '@/utils/el_table_content_width_adaptation'


//el-table表格内容宽度自适应
Vue.prototype.elTableAdaptationWidth = elTableAdaptationWidth.flexColumnWidth

然后在页面中直接调用就可以了:

html 复制代码
<el-table>
<el-table-column 
        v-for="item in tableList" 
        :label="item.label" 
        :prop="item.prop"
        :width="elTableAdaptationWidth(item.label,item.prop,tableList)"
        />
</el-table>

效果如下:

相关推荐
IT_陈寒4 分钟前
JavaScript项目实战经验分享
前端·人工智能·后端
用户47949283569151 小时前
6w star,GitHub 趋势第一的 Ponytail,这个agent插件到底在火什么
前端·后端
薛定喵的谔2 小时前
我开源了一个精致的 Next.js 博客模板:Skyplume
前端·前端框架·next.js
张龙6873 小时前
构建生产级 AI Agent:工具调用与记忆架构实战指南
前端
kyriewen4 小时前
2026 年了,还在用 Node.js?Bun 迁移实战:20 分钟搞定,附踩坑记录
前端·javascript·node.js
青山Coding5 小时前
Cesium应用(八):物体运动的实现思路
前端·cesium
用户41659673693555 小时前
Android WebView 加载 file:// 离线页面调试教程
android·前端
Asmewill5 小时前
curl命令学习笔记一
前端
我是一只快乐的小螃蟹5 小时前
1.2 ArrayList 源码解析
前端
星栈5 小时前
我用 Rust + Dioxus 做了个全栈跨平台笔记应用:再把新建、编辑和交付补上
前端·rust·前端框架