插件窝 干货文章 Element UI el-table单元格文本如何实现自动换行?

Element UI el-table单元格文本如何实现自动换行?

table 样式 template tooltip 773    来源:    2025-03-22

在 Element UI 的 el-table 组件中,默认情况下单元格内的文本不会自动换行。如果你希望单元格内的文本能够自动换行,可以通过以下几种方式实现:

方法一:使用 CSS 样式

你可以通过自定义 CSS 样式来实现单元格文本的自动换行。

  1. 全局样式: 在你的全局样式文件(如 styles.cssApp.vue 中的 <style> 标签)中添加以下样式:

    .el-table .cell {
     white-space: pre-wrap; /* 保留空白符,允许换行 */
     word-break: break-all; /* 允许在单词内换行 */
    }
    
  2. 局部样式: 如果你只想对特定的表格应用自动换行样式,可以在该表格的父元素上添加一个类名,然后针对该类名设置样式:

    <template>
     <el-table class="auto-wrap-table">
       <!-- 表格内容 -->
     </el-table>
    </template>
    
    <style scoped>
    .auto-wrap-table .el-table .cell {
     white-space: pre-wrap;
     word-break: break-all;
    }
    </style>
    

方法二:使用 :show-overflow-tooltip 属性

如果你希望在文本超出单元格宽度时显示省略号,并且鼠标悬停时显示完整内容,可以使用 :show-overflow-tooltip 属性。

<template>
  <el-table :data="tableData">
    <el-table-column
      prop="content"
      label="内容"
      :show-overflow-tooltip="true">
    </el-table-column>
  </el-table>
</template>

方法三:自定义单元格内容

如果你需要更复杂的布局或样式,可以通过 scoped slot 自定义单元格内容,并在其中使用 HTML 和 CSS 实现自动换行。

<template>
  <el-table :data="tableData">
    <el-table-column
      prop="content"
      label="内容">
      <template slot-scope="scope">
        <div style="white-space: pre-wrap; word-break: break-all;">
          {{ scope.row.content }}
        </div>
      </template>
    </el-table-column>
  </el-table>
</template>

方法四:使用 el-tooltip 组件

如果你希望在文本超出单元格宽度时显示提示框,可以使用 el-tooltip 组件。

<template>
  <el-table :data="tableData">
    <el-table-column
      prop="content"
      label="内容">
      <template slot-scope="scope">
        <el-tooltip :content="scope.row.content" placement="top">
          <div style="white-space: pre-wrap; word-break: break-all;">
            {{ scope.row.content }}
          </div>
        </el-tooltip>
      </template>
    </el-table-column>
  </el-table>
</template>

总结

  • CSS 样式:适用于全局或局部的自动换行需求。
  • :show-overflow-tooltip:适用于文本超出时显示提示框的需求。
  • 自定义单元格内容:适用于需要更复杂布局或样式的场景。
  • el-tooltip 组件:适用于需要显示提示框的场景。

根据你的具体需求选择合适的方法即可。