feat(components): [table-column] preserve expanded content (#19899)

* feat: [table-column] preserve expanded content

* chore: format

---------

Co-authored-by: warmthsea <2586244885@qq.com>
This commit is contained in:
EralChen
2025-03-13 10:20:07 +08:00
committed by GitHub
parent 7dbac0e1bc
commit d410486c07
5 changed files with 241 additions and 83 deletions

View File

@@ -181,6 +181,8 @@ table/custom-header
When the row content is too long and you do not want to display the horizontal scroll bar, you can use the expandable row feature.
After ^(2.9.7), `preserve-expanded-content` is added to control whether to preserve expanded row content in DOM when collapsed.
:::demo Activate expandable row by adding type="expand" and slot. The template for el-table-column will be rendered as the contents of the expanded row, and you can access the same attributes as when you are using `slot` in custom column templates.
table/expandable-row
@@ -257,50 +259,51 @@ table/tooltip-formatter
### Table Attributes
| Name | Description | Type | Default |
| ------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| data | table data | ^[array]`any[]` | [] |
| height | table's height. By default it has an `auto` height. If its value is a number, the height is measured in pixels; if its value is a string, the value will be assigned to element's style.height, the height is affected by external styles | ^[string] / ^[number] | — |
| max-height | table's max-height. The legal value is a number or the height in px | ^[string] / ^[number] | — |
| stripe | whether Table is striped | ^[boolean] | false |
| border | whether Table has vertical border | ^[boolean] | false |
| size | size of Table | ^[enum]`'' \| 'large' \| 'default' \| 'small'` | — |
| fit | whether width of column automatically fits its container | ^[boolean] | true |
| show-header | whether Table header is visible | ^[boolean] | true |
| highlight-current-row | whether current row is highlighted | ^[boolean] | false |
| current-row-key | key of current row, a set only prop | ^[string] / ^[number] | — |
| row-class-name | function that returns custom class names for a row, or a string assigning class names for every row | ^[Function]`(data: { row: any, rowIndex: number }) => string` / ^[string] | — |
| row-style | function that returns custom style for a row, or an object assigning custom style for every row | ^[Function]`(data: { row: any, rowIndex: number }) => CSSProperties` / ^[object]`CSSProperties` | — |
| cell-class-name | function that returns custom class names for a cell, or a string assigning class names for every cell | ^[Function]`(data: { row: any, column: any, rowIndex: number, columnIndex: number }) => string` / ^[string] | — |
| cell-style | function that returns custom style for a cell, or an object assigning custom style for every cell | ^[Function]`(data: { row: any, column: any, rowIndex: number, columnIndex: number }) => CSSProperties` / ^[object]`CSSProperties` | — |
| header-row-class-name | function that returns custom class names for a row in table header, or a string assigning class names for every row in table header | ^[Function]`(data: { row: any, rowIndex: number }) => string` / ^[string] | — |
| header-row-style | function that returns custom style for a row in table header, or an object assigning custom style for every row in table header | ^[Function]`(data: { row: any, rowIndex: number }) => CSSProperties` / ^[object]`CSSProperties` | — |
| header-cell-class-name | function that returns custom class names for a cell in table header, or a string assigning class names for every cell in table header | ^[Function]`(data: { row: any, column: any, rowIndex: number, columnIndex: number }) => string` / ^[string] | — |
| header-cell-style | function that returns custom style for a cell in table header, or an object assigning custom style for every cell in table header | ^[Function]`(data: { row: any, column: any, rowIndex: number, columnIndex: number }) => CSSProperties` / ^[object]`CSSProperties` | — |
| row-key | key of row data, used for optimizing rendering. Required if `reserve-selection` is on or display tree data. When its type is String, multi-level access is supported, e.g. `user.info.id`, but `user.info[0].id` is not supported, in which case `Function` should be used | ^[function]`(row: any) => string` / ^[string] | — |
| empty-text | displayed text when data is empty. You can customize this area with `#empty` | ^[string] | No Data |
| default-expand-all | whether expand all rows by default, works when the table has a column type="expand" or contains tree structure data | ^[boolean] | false |
| expand-row-keys | set expanded rows by this prop, prop's value is the keys of expand rows, you should set row-key before using this prop | ^[array]`string[]` | — |
| default-sort | set the default sort column and order. property `prop` is used to set default sort column, property `order` is used to set default sort order | ^[object]`Sort` | if `prop` is set, and `order` is not set, then `order` is default to ascending |
| tooltip-effect | the `effect` of the overflow tooltip | ^[enum]`'dark' \| 'light'` | dark |
| tooltip-options ^(2.2.28) | the options for the overflow tooltip, [see the following tooltip component](tooltip.html#attributes) | ^[object]`Pick<ElTooltipProps, 'effect' \| 'enterable' \| 'hideAfter' \| 'offset' \| 'placement' \| 'popperClass' \| 'popperOptions' \| 'showAfter' \| 'showArrow'>` | ^[object]`{ enterable: true, placement: 'top', showArrow: true, hideAfter: 200, popperOptions: { strategy: 'fixed' } }` |
| append-filter-panel-to ^(2.8.4) | which element the filter panels appends to | ^[string] | — |
| show-summary | whether to display a summary row | ^[boolean] | false |
| sum-text | displayed text for the first column of summary row | ^[string] | Sum |
| summary-method | custom summary method | ^[Function]`(data: { columns: any[], data: any[] }) => (VNode \| string)[]` | — |
| span-method | method that returns rowspan and colspan | ^[Function]`(data: { row: any, column: any, rowIndex: number, columnIndex: number }) => number[] \| { rowspan: number, colspan: number } \| void` | — |
| select-on-indeterminate | controls the behavior of master checkbox in multi-select tables when only some rows are selected (but not all). If true, all rows will be selected, else deselected | ^[boolean] | true |
| indent | horizontal indentation of tree data | ^[number] | 16 |
| lazy | whether to lazy loading data | ^[boolean] | false |
| load | method for loading child row data, only works when `lazy` is true | ^[Function]`(row: any, treeNode: TreeNode, resolve: (data: any[]) => void) => void` | — |
| tree-props | configuration for rendering nested data | ^[object]`{ hasChildren?: string, children?: string, checkStrictly?: boolean }` | ^[object]`{ hasChildren: 'hasChildren', children: 'children', checkStrictly: false }` |
| table-layout | sets the algorithm used to lay out table cells, rows, and columns | ^[enum]`'fixed' \| 'auto'` | fixed |
| scrollbar-always-on | always show scrollbar | ^[boolean] | false |
| show-overflow-tooltip | whether to hide extra content and show them in a tooltip when hovering on the cell.It will affect all the table columns, refer to table [tooltip-options](#table-attributes) | ^[boolean] / [`object`](#table-attributes) ^(2.3.7) | — |
| flexible ^(2.2.1) | ensure main axis minimum-size doesn't follow the content | ^[boolean] | false |
| scrollbar-tabindex ^(2.8.3) | body scrollbar's wrap container tabindex | ^[string] / ^[number] | — |
| allow-drag-last-column ^(2.9.2) | whether to allow drag the last column | ^[boolean] | true |
| tooltip-formatter ^(2.9.4) | customize tooltip content when using `show-overflow-tooltip` | ^[Function]`(data: { row: any, column: any, cellValue: any }) => VNode \| string` | — |
| Name | Description | Type | Default |
| ---------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| data | table data | ^[array]`any[]` | [] |
| height | table's height. By default it has an `auto` height. If its value is a number, the height is measured in pixels; if its value is a string, the value will be assigned to element's style.height, the height is affected by external styles | ^[string] / ^[number] | — |
| max-height | table's max-height. The legal value is a number or the height in px | ^[string] / ^[number] | — |
| stripe | whether Table is striped | ^[boolean] | false |
| border | whether Table has vertical border | ^[boolean] | false |
| size | size of Table | ^[enum]`'' \| 'large' \| 'default' \| 'small'` | — |
| fit | whether width of column automatically fits its container | ^[boolean] | true |
| show-header | whether Table header is visible | ^[boolean] | true |
| highlight-current-row | whether current row is highlighted | ^[boolean] | false |
| current-row-key | key of current row, a set only prop | ^[string] / ^[number] | — |
| row-class-name | function that returns custom class names for a row, or a string assigning class names for every row | ^[Function]`(data: { row: any, rowIndex: number }) => string` / ^[string] | — |
| row-style | function that returns custom style for a row, or an object assigning custom style for every row | ^[Function]`(data: { row: any, rowIndex: number }) => CSSProperties` / ^[object]`CSSProperties` | — |
| cell-class-name | function that returns custom class names for a cell, or a string assigning class names for every cell | ^[Function]`(data: { row: any, column: any, rowIndex: number, columnIndex: number }) => string` / ^[string] | — |
| cell-style | function that returns custom style for a cell, or an object assigning custom style for every cell | ^[Function]`(data: { row: any, column: any, rowIndex: number, columnIndex: number }) => CSSProperties` / ^[object]`CSSProperties` | — |
| header-row-class-name | function that returns custom class names for a row in table header, or a string assigning class names for every row in table header | ^[Function]`(data: { row: any, rowIndex: number }) => string` / ^[string] | — |
| header-row-style | function that returns custom style for a row in table header, or an object assigning custom style for every row in table header | ^[Function]`(data: { row: any, rowIndex: number }) => CSSProperties` / ^[object]`CSSProperties` | — |
| header-cell-class-name | function that returns custom class names for a cell in table header, or a string assigning class names for every cell in table header | ^[Function]`(data: { row: any, column: any, rowIndex: number, columnIndex: number }) => string` / ^[string] | — |
| header-cell-style | function that returns custom style for a cell in table header, or an object assigning custom style for every cell in table header | ^[Function]`(data: { row: any, column: any, rowIndex: number, columnIndex: number }) => CSSProperties` / ^[object]`CSSProperties` | — |
| row-key | key of row data, used for optimizing rendering. Required if `reserve-selection` is on or display tree data. When its type is String, multi-level access is supported, e.g. `user.info.id`, but `user.info[0].id` is not supported, in which case `Function` should be used | ^[function]`(row: any) => string` / ^[string] | — |
| empty-text | displayed text when data is empty. You can customize this area with `#empty` | ^[string] | No Data |
| default-expand-all | whether expand all rows by default, works when the table has a column type="expand" or contains tree structure data | ^[boolean] | false |
| expand-row-keys | set expanded rows by this prop, prop's value is the keys of expand rows, you should set row-key before using this prop | ^[array]`string[]` | — |
| default-sort | set the default sort column and order. property `prop` is used to set default sort column, property `order` is used to set default sort order | ^[object]`Sort` | if `prop` is set, and `order` is not set, then `order` is default to ascending |
| tooltip-effect | the `effect` of the overflow tooltip | ^[enum]`'dark' \| 'light'` | dark |
| tooltip-options ^(2.2.28) | the options for the overflow tooltip, [see the following tooltip component](tooltip.html#attributes) | ^[object]`Pick<ElTooltipProps, 'effect' \| 'enterable' \| 'hideAfter' \| 'offset' \| 'placement' \| 'popperClass' \| 'popperOptions' \| 'showAfter' \| 'showArrow'>` | ^[object]`{ enterable: true, placement: 'top', showArrow: true, hideAfter: 200, popperOptions: { strategy: 'fixed' } }` |
| append-filter-panel-to ^(2.8.4) | which element the filter panels appends to | ^[string] | — |
| show-summary | whether to display a summary row | ^[boolean] | false |
| sum-text | displayed text for the first column of summary row | ^[string] | Sum |
| summary-method | custom summary method | ^[Function]`(data: { columns: any[], data: any[] }) => (VNode \| string)[]` | — |
| span-method | method that returns rowspan and colspan | ^[Function]`(data: { row: any, column: any, rowIndex: number, columnIndex: number }) => number[] \| { rowspan: number, colspan: number } \| void` | — |
| select-on-indeterminate | controls the behavior of master checkbox in multi-select tables when only some rows are selected (but not all). If true, all rows will be selected, else deselected | ^[boolean] | true |
| indent | horizontal indentation of tree data | ^[number] | 16 |
| lazy | whether to lazy loading data | ^[boolean] | false |
| load | method for loading child row data, only works when `lazy` is true | ^[Function]`(row: any, treeNode: TreeNode, resolve: (data: any[]) => void) => void` | — |
| tree-props | configuration for rendering nested data | ^[object]`{ hasChildren?: string, children?: string, checkStrictly?: boolean }` | ^[object]`{ hasChildren: 'hasChildren', children: 'children', checkStrictly: false }` |
| table-layout | sets the algorithm used to lay out table cells, rows, and columns | ^[enum]`'fixed' \| 'auto'` | fixed |
| scrollbar-always-on | always show scrollbar | ^[boolean] | false |
| show-overflow-tooltip | whether to hide extra content and show them in a tooltip when hovering on the cell.It will affect all the table columns, refer to table [tooltip-options](#table-attributes) | ^[boolean] / [`object`](#table-attributes) ^(2.3.7) | — |
| flexible ^(2.2.1) | ensure main axis minimum-size doesn't follow the content | ^[boolean] | false |
| scrollbar-tabindex ^(2.8.3) | body scrollbar's wrap container tabindex | ^[string] / ^[number] | — |
| allow-drag-last-column ^(2.9.2) | whether to allow drag the last column | ^[boolean] | true |
| tooltip-formatter ^(2.9.4) | customize tooltip content when using `show-overflow-tooltip` | ^[Function]`(data: { row: any, column: any, cellValue: any }) => VNode \| string` | — |
| preserve-expanded-content ^(2.9.7) | whether to preserve expanded row content in DOM when collapsed | ^[boolean] | false |
### Table Events

View File

@@ -1,7 +1,13 @@
<template>
switch parent border: <el-switch v-model="parentBorder" /> switch child
border: <el-switch v-model="childBorder" />
<el-table :data="tableData" :border="parentBorder" style="width: 100%">
border: <el-switch v-model="childBorder" /> preserve expanded:
<el-switch v-model="preserveExpanded" />
<el-table
:data="tableData"
:border="parentBorder"
:preserve-expanded-content="preserveExpanded"
style="width: 100%"
>
<el-table-column type="expand">
<template #default="props">
<div m="4">
@@ -30,6 +36,7 @@ import { ref } from 'vue'
const parentBorder = ref(false)
const childBorder = ref(false)
const preserveExpanded = ref(false)
const tableData = [
{
date: '2016-05-03',

View File

@@ -633,6 +633,150 @@ describe('table column', () => {
})
})
describe('column expand', () => {
const createInstance = function (extra?) {
extra = extra || ''
return mount({
components: {
ElTableColumn,
ElTable,
},
template: `
<el-table row-key="id" :data="testData" @expand-change="handleExpand" ${extra}>
<el-table-column type="expand">
<template #default="props">
<div>{{props.row.name}}</div>
</template>
</el-table-column>
<el-table-column prop="release" label="release" />
<el-table-column prop="director" label="director" />
<el-table-column prop="runtime" label="runtime" />
</el-table>
`,
data() {
return {
expandCount: 0,
expandRowKeys: [],
testData: getTestData(),
}
},
methods: {
handleExpand() {
this.expandCount++
},
refreshData() {
this.testData = getTestData()
},
},
})
}
it('should render expand column correctly', async () => {
const wrapper = createInstance()
await doubleWait()
expect(wrapper.findAll('td.el-table__expand-column').length).toEqual(5)
wrapper.unmount()
})
describe('preserve-expanded-content', () => {
it('should lose expanded state when refreshing data without preserve-expanded-content', async () => {
const wrapper = createInstance() // No preserve-expanded-content prop
await doubleWait()
// Click expand icon and verify initial state
const expandIcon = wrapper.find('.el-table__expand-icon')
await expandIcon.trigger('click')
await doubleWait()
expect(wrapper.findAll('.el-table__expanded-cell')).toHaveLength(1)
// Clear and replace data
wrapper.vm.testData = []
await doubleWait()
wrapper.vm.testData = getTestData()
await doubleWait()
// Without preserve-expanded-content, expanded state should be lost
expect(wrapper.findAll('.el-table__expanded-cell')).toHaveLength(0)
// All expand icons should be in collapsed state
expect(
wrapper.find('.el-table__expand-icon--expanded').exists()
).toBeFalsy()
wrapper.unmount()
})
it('should preserve expanded state when refreshing data with preserve-expanded-content', async () => {
const wrapper = createInstance('preserve-expanded-content')
await doubleWait()
// First expand the row
const expandEl = wrapper.find('.el-table__expand-icon')
await expandEl.trigger('click')
// Verify initial expand
expect(wrapper.find('.el-table__expanded-cell').exists()).toBeTruthy()
const expandedContent = wrapper.find('.el-table__expanded-cell').text()
expect(expandedContent).toContain(wrapper.vm.testData[0].name)
// Refresh data
wrapper.vm.refreshData()
await doubleWait()
// With preserve-expanded-content, expanded state and content should persist
expect(wrapper.find('.el-table__expanded-cell').exists()).toBeTruthy()
expect(wrapper.find('.el-table__expanded-cell').text()).toBe(
expandedContent
)
wrapper.unmount()
})
it('should preserve multiple expanded rows when refreshing data', async () => {
const wrapper = createInstance('preserve-expanded-content')
await doubleWait()
// Find first two expand icons
const expandIcons = wrapper
.findAll('.el-table__expand-icon')
.slice(0, 2)
// Expand first two rows
for (const icon of expandIcons) {
await icon.trigger('click')
await doubleWait()
}
// Verify both rows are expanded
const expandedIcons = wrapper.findAll(
'.el-table__expand-icon--expanded'
)
expect(expandedIcons).toHaveLength(2)
// Store expanded content
const expandedRows = wrapper.findAll('.el-table__expanded-cell')
const initialContents = expandedRows.map((row) => row.text())
// Replace data with new reference
wrapper.vm.testData = [...getTestData()]
await doubleWait()
// Verify expansions and content are preserved
const expandedIconsAfter = wrapper.findAll(
'.el-table__expand-icon--expanded'
)
expect(expandedIconsAfter).toHaveLength(2)
const expandedRowsAfter = wrapper.findAll('.el-table__expanded-cell')
const preservedContents = expandedRowsAfter.map((row) => row.text())
expect(preservedContents).toEqual(initialContents)
wrapper.unmount()
})
})
})
describe('multi level column', () => {
it('should works', async () => {
const wrapper = mount({

View File

@@ -59,11 +59,7 @@ function useRender<T>(props: Partial<TableBodyProps<T>>) {
rowClasses.push(ns.em('row', `level-${treeRowData.level}`))
display = treeRowData.display
}
const displayStyle = display
? null
: {
display: 'none',
}
const displayStyle = display ? null : { display: 'none' }
return h(
'tr',
{
@@ -157,39 +153,40 @@ function useRender<T>(props: Partial<TableBodyProps<T>>) {
const expanded = isRowExpanded(row)
const tr = rowRender(row, $index, undefined, expanded)
const renderExpanded = parent.renderExpanded
if (expanded) {
if (!renderExpanded) {
console.error('[Element Error]renderExpanded is required.')
return tr
}
// 使用二维数组,避免修改 $index
// Use a matrix to avoid modifying $index
return [
[
tr,
h(
'tr',
{
key: `expanded-row__${tr.key as string}`,
},
[
h(
'td',
{
colspan: columns.length,
class: `${ns.e('cell')} ${ns.e('expanded-cell')}`,
},
[renderExpanded({ row, $index, store, expanded })]
),
]
),
],
]
} else {
// 使用二维数组,避免修改 $index
// Use a two dimensional array avoid modifying $index
return [[tr]]
if (!renderExpanded) {
console.error('[Element Error]renderExpanded is required.')
return tr
}
// 在没设置时候避免 h 执行
// 非保留模式且未展开时,直接返回
// 使用二维数组包装,避免修改 $index
const rows = [[tr]]
// 仅在需要时创建展开行(保留模式或展开状态)
if (parent.props.preserveExpandedContent || expanded) {
rows[0].push(
h(
'tr',
{
key: `expanded-row__${tr.key as string}`,
style: { display: expanded ? '' : 'none' },
},
[
h(
'td',
{
colspan: columns.length,
class: `${ns.e('cell')} ${ns.e('expanded-cell')}`,
},
[renderExpanded({ row, $index, store, expanded })]
),
]
)
)
}
return rows
} else if (Object.keys(treeData.value).length) {
assertRowKey()
// TreeTable 时rowKey 必须由用户设定,不使用 getKeyOfRow 计算

View File

@@ -414,6 +414,13 @@ export default {
type: Boolean,
default: true,
},
/**
* @description whether to preserve expanded row content in DOM when collapsed
*/
preserveExpandedContent: {
type: Boolean,
default: false,
},
}
export type {
SummaryMethod,