插件窝 干货文章 Element UI el-table单元格换行这么难?如何轻松实现多行文本显示?

Element UI el-table单元格换行这么难?如何轻松实现多行文本显示?

table style column el 543    来源:    2025-03-19

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

1. 使用 :show-overflow-tooltip 属性

el-table 提供了 :show-overflow-tooltip 属性,当内容超出单元格宽度时,会显示一个 tooltip。虽然这不是真正的换行,但在某些情况下可以满足需求。

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

2. 使用 CSS 样式强制换行

你可以通过 CSS 样式来强制单元格内容换行。具体做法是给 el-table 的单元格添加 white-space: normal; 样式。

<el-table :data="tableData" style="width: 100%">
  <el-table-column prop="content" label="内容">
    <template slot-scope="scope">
      <div style="white-space: normal;">
        {{ scope.row.content }}
      </div>
    </template>
  </el-table-column>
</el-table>

3. 使用 el-table-columnformatter 属性

你可以使用 formatter 属性来自定义单元格内容的显示方式,结合 HTML 标签实现换行。

<el-table :data="tableData" style="width: 100%">
  <el-table-column prop="content" label="内容" :formatter="formatContent"></el-table-column>
</el-table>

<script>
export default {
  methods: {
    formatContent(row, column, cellValue) {
      return cellValue.replace(/\n/g, '<br>');
    }
  }
}
</script>

4. 使用 el-tablecell-style 属性

你可以通过 cell-style 属性来动态设置单元格的样式,从而实现换行。

<el-table :data="tableData" style="width: 100%">
  <el-table-column prop="content" label="内容" :cell-style="{ 'white-space': 'normal' }"></el-table-column>
</el-table>

5. 使用 el-tableheader-cell-stylecell-style 属性

如果你希望表头和单元格都支持换行,可以同时使用 header-cell-stylecell-style 属性。

<el-table :data="tableData" style="width: 100%">
  <el-table-column
    prop="content"
    label="内容"
    :header-cell-style="{ 'white-space': 'normal' }"
    :cell-style="{ 'white-space': 'normal' }"
  ></el-table-column>
</el-table>

6. 使用 el-tableslot-scope 自定义内容

你可以使用 slot-scope 来自定义单元格内容,结合 HTML 标签实现换行。

<el-table :data="tableData" style="width: 100%">
  <el-table-column prop="content" label="内容">
    <template slot-scope="scope">
      <div style="white-space: pre-line;">{{ scope.row.content }}</div>
    </template>
  </el-table-column>
</el-table>

7. 使用 el-tablerow-style 属性

如果你希望整个行的内容都支持换行,可以使用 row-style 属性。

<el-table :data="tableData" style="width: 100%" :row-style="{ 'white-space': 'normal' }">
  <el-table-column prop="content" label="内容"></el-table-column>
</el-table>

总结

通过以上几种方式,你可以轻松实现 el-table 单元格内容的多行显示。根据你的具体需求,选择最适合的方式即可。