在 Element UI 的 el-table
组件中,默认情况下,单元格内容是不会自动换行的。如果你希望在单元格中显示多行文本,可以通过以下几种方式来实现:
: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>
你可以通过 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>
el-table-column
的 formatter
属性你可以使用 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>
el-table
的 cell-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>
el-table
的 header-cell-style
和 cell-style
属性如果你希望表头和单元格都支持换行,可以同时使用 header-cell-style
和 cell-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>
el-table
的 slot-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>
el-table
的 row-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
单元格内容的多行显示。根据你的具体需求,选择最适合的方式即可。