返回正文
Are you an LLM? You can read better optimized documentation at /zh-CN/blog/2025-08/ant-table-auto-height.md for this page in Markdown format
Ant Design Vue Table 高度自适应
不包含固定列
scss
.auto-scroll-table .ant-table-body {
overflow-y: auto !important;
}
1
2
3
2
3
vue
<a-table
:columns="myData.columns"
defaultExpandAllRows
:loading
ref="tableRef"
:key="tableKey"
class="auto-scroll-table"
:scroll="{ x: 'max-content', y: 'calc(100vh - 230px)' }"
:locale="{ emptyText: '未找到符合条件的组织' }"
:dataSource="myData.dataSource"
@expandedRowsChange="handleRowExpanded"
bordered
rowKey="organizationId"
size="small"
:pagination="false"></a-table>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
包含固定列
通过比较外部容器和表格的高度值,进行判断是否需要出现滚动条。
同时,需要在表格折叠的同时刷新高度。
ts
// @ts-ignore
import { debounce } from 'lodash-es'
import {
onBeforeUnmount,
onMounted,
ref,
toRaw,
unref,
type ComponentPublicInstance,
type Ref,
nextTick
} from 'vue'
type TableElementRef = Ref<HTMLElement | ComponentPublicInstance | null>
type TableContainerElementRef = Ref<HTMLElement | null>
// 安全获取表格DOM元素
function resolveTableElement(
elRef: HTMLElement | ComponentPublicInstance | null
): HTMLElement | null {
if (!elRef) return null
// 处理Vue组件实例
if (typeof elRef === 'object' && '$el' in elRef) {
const component = elRef as ComponentPublicInstance
// 针对Ant Design Vue Table组件获取内部表格容器
const tableContainer = component.$el.querySelector?.('.ant-table-container')
if (tableContainer) return tableContainer as HTMLElement
return component.$el as HTMLElement
}
return elRef as HTMLElement
}
export function useTableAutoHeight(
tableRef: TableElementRef,
tableContainerRef: TableContainerElementRef
) {
const tableScroll = ref<{ x?: string | 'max-content'; y?: string }>({})
const resetScroll = () => {
tableScroll.value = { x: 'max-content', y: undefined }
}
let resizeObserver: ResizeObserver | null = null
// 精确获取表格滚动容器
const getScrollContainer = (): HTMLElement | null => {
const tableEl = resolveTableElement(toRaw(unref(tableRef)))
if (!tableEl) return null
// 尝试查找 Ant Design Vue 的滚动容器
const scrollContainer =
tableEl.querySelector?.('.ant-table-tbody') ||
tableEl.querySelector?.('.ant-table-content')
return scrollContainer as HTMLElement | null
}
// 检查是否显示垂直滚动条
const hasVerticalScrollbar = (container: HTMLElement): boolean => {
if (!container) return false
// 计算滚动条宽度差
const scrollbarVisible = container.scrollHeight > container.clientHeight
const scrollbarWidth = scrollbarVisible
? container.offsetWidth - container.clientWidth
: 0
// 确认是否有内容溢出
const contentOverflow =
container.scrollHeight > container.clientHeight + scrollbarWidth
return contentOverflow
}
// 计算表格动态高度
function calculateTableHeight() {
const container = getScrollContainer()
if (!container) return
resetScroll()
// 获取容器位置
const containerRect = tableContainerRef.value!.getBoundingClientRect()
const windowHeight = document.documentElement.clientHeight
const bottomMargin = 80 // 底部安全边距
// 计算可视区域可用高度
const maxVisibleHeight = tableContainerRef.value!.clientHeight
const maxVisibleWidth = tableContainerRef.value!.clientWidth
// 检查是否需要滚动条
// hasVerticalScrollbar(container)
if (container.clientHeight > maxVisibleHeight) {
tableScroll.value = {
x: 'max-content',
y: `calc(100vh - 230px)`
}
} else {
// 不需要滚动条时,不设置y属性
tableScroll.value = { x: 'max-content', y: undefined }
}
}
// 防抖计算函数
const debouncedCalc = debounce(
() => {
calculateTableHeight()
},
200,
{ leading: true }
)
// 初始化并设置监听
const initHeightCalculation = () => {
// 确保DOM加载完成
nextTick(() => {
debouncedCalc()
// // 使用ResizeObserver监听表格容器变化
// const container = resolveTableElement(toRaw(unref(tableRef)))
// if (container) {
// if (resizeObserver) resizeObserver.disconnect()
// resizeObserver = new ResizeObserver(debouncedCalc)
// resizeObserver.observe(container)
// // 监听滚动容器变化
// const scrollContainer = container.querySelector('.ant-table-body')
// if (scrollContainer) {
// resizeObserver.observe(scrollContainer)
// }
// }
})
}
// 组件挂载时设置监听
onMounted(() => {
initHeightCalculation()
window.addEventListener('resize', debouncedCalc)
})
// 组件卸载时清理
onBeforeUnmount(() => {
if (resizeObserver) {
resizeObserver.disconnect()
resizeObserver = null
}
window.removeEventListener('resize', debouncedCalc)
debouncedCalc.cancel()
})
// 提供手动刷新方法
return {
scroll: tableScroll,
recalculate: debouncedCalc
}
}
// import { debounce } from 'lodash-es'
// import { markRaw, nextTick, onBeforeUnmount, onMounted, ref, toRaw, unref, type Ref } from 'vue'
// export function useTableHeight(tableRef: Ref<HTMLElement | null>) {
// const tableSrcoll = ref<{
// x?: string
// y?: string
// }>()
// const getRawElement = () => {
// if (!tableRef.value) return null
// return toRaw(tableRef.value) // 返回原始 DOM 元素
// }
// // 计算表格动态高度
// function calculateTableHeight() {
// if (tableRef.value) {
// console.log('tableRef.value', unref(tableRef.value))
// const tableEl = unref(tableRef.value)
// console.log('tableEl', tableEl)
// const bodyEl = tableEl.querySelector('.ant-table')
// console.log('bodyEl', bodyEl)
// if (bodyEl) {
// console.log(bodyEl.scrollHeight, bodyEl.clientHeight)
// if (bodyEl.scrollHeight > bodyEl.clientHeight) {
// // 内容超出时设置固定高度(触发滚动条)
// tableSrcoll.value = { x: 'max-content', y: 'calc(100vh - 250px)' }
// } else {
// tableSrcoll.value = { x: 'max-content' }
// }
// }
// }
// }
// // 初始化和监听 resize 事件,这里使用防抖提高性能
// onMounted(() => {
// nextTick(() => {
// calculateTableHeight()
// })
// window.addEventListener('resize', debounce(calculateTableHeight, 200))
// })
// // 移除监听器
// onBeforeUnmount(() => {
// window.removeEventListener('resize', debounce(calculateTableHeight, 300))
// })
// return {
// tableSrcoll
// }
// }
// // useTableAutoHeight.ts
// import {
// type Ref,
// ref,
// onMounted,
// onUnmounted,
// nextTick,
// watch,
// type ComponentPublicInstance
// } from 'vue'
// interface TableAutoHeightOptions {
// extraHeight?: number // 额外需要减去的高度(如表单、按钮等)
// minHeight?: number // 最小高度
// maxHeight?: number // 最大高度
// debounceTime?: number // 防抖时间(ms)
// observeResize?: boolean // 是否监听窗口变化
// observeElements?: HTMLElement[] // 需要监听的其他元素
// }
// interface TableAutoHeightReturn {
// scroll: Ref<{ x?: string | number | 'max-content'; y?: string|number }>
// refreshHeight: () => void // 手动刷新高度的函数
// }
// export default function useTableAutoHeight(
// tableRef: Ref<ComponentPublicInstance | null>,
// options: TableAutoHeightOptions = {}
// ): TableAutoHeightReturn {
// // 合并默认选项
// const {
// extraHeight = 0,
// minHeight = 100,
// maxHeight = Infinity,
// debounceTime = 100,
// observeResize = true,
// observeElements = []
// } = options
// const tableScroll = ref<{ x?: string | 'max-content'; y?: string }>({})
// // 安全获取表格容器元素
// const getTableContainer = (): HTMLElement | null => {
// if (!tableRef.value) return null
// try {
// // 获取表格根元素
// const tableRoot = tableRef.value.$el as HTMLElement
// console.log('tableRoot', tableRoot)
// if (!tableRoot) return null
// // 获取表格容器
// const container = tableRoot.querySelector(
// '.ant-table-container'
// ) as HTMLElement
// console.log('container', container)
// return container
// } catch (error) {
// console.error('获取表格容器失败:', error)
// return null
// }
// }
// // 计算表格高度
// const calculateHeight = (): void => {
// const container = getTableContainer()
// if (!container) {
// console.log('not found containere')
// return
// }
// try {
// // 获取表格容器的高度
// const containerHeight = container.clientHeight
// // 计算表格内容区域高度
// let contentHeight = containerHeight
// // 减去表头高度
// const header = container.querySelector('.ant-table-thead') as HTMLElement
// if (header) {
// contentHeight -= header.offsetHeight
// }
// // 减去分页高度(如果存在)
// const pagination = container.querySelector(
// '.ant-pagination'
// ) as HTMLElement
// if (pagination) {
// contentHeight -= pagination.offsetHeight
// }
// // 减去额外高度
// contentHeight -= extraHeight
// // 应用最小和最大高度限制
// let finalHeight = Math.max(minHeight, contentHeight)
// finalHeight = Math.min(maxHeight, finalHeight)
// // 获取表格主体
// const tableBody =
// container.querySelector?.('.ant-table-body') ||
// (container.querySelector?.('.ant-table-content') as HTMLElement)
// console.log(tableBody.scrollHeight, contentHeight)
// // 只有当内容高度大于可用高度时才设置滚动条
// if (tableBody && tableBody.scrollHeight > contentHeight) {
// tableScroll.value.y = `${contentHeight}px`
// } else {
// tableScroll.value.y = undefined
// }
// } catch (error) {
// console.error('计算表格高度出错:', error)
// }
// }
// // 防抖函数
// let debounceTimer: ReturnType<typeof setTimeout> | null = null
// const debouncedCalculate = (): void => {
// if (debounceTimer) {
// clearTimeout(debounceTimer)
// }
// debounceTimer = setTimeout(() => {
// nextTick(calculateHeight)
// }, debounceTime)
// }
// // 监听器引用,用于卸载时清理
// let resizeObserver: ResizeObserver | null = null
// let mutationObserver: MutationObserver | null = null
// // 初始化监听
// onMounted(() => {
// // 初始计算高度
// debouncedCalculate()
// // 监听窗口大小变化
// if (observeResize) {
// window.addEventListener('resize', debouncedCalculate)
// }
// // 监听容器大小变化
// const container = getTableContainer()
// if (container) {
// resizeObserver = new ResizeObserver(debouncedCalculate)
// resizeObserver.observe(container)
// // 监听固定列容器变化
// const fixedColumns = container.querySelectorAll('.ant-table-fixed')
// fixedColumns.forEach(fixedCol => {
// resizeObserver?.observe(fixedCol as HTMLElement)
// })
// }
// // 监听其他元素变化
// if (observeElements.length > 0 || container) {
// mutationObserver = new MutationObserver(debouncedCalculate)
// // 观察表格容器变化
// if (container) {
// mutationObserver.observe(container, {
// childList: true,
// subtree: true
// })
// }
// // 观察其他指定元素
// observeElements.forEach(el => {
// if (el) {
// mutationObserver?.observe(el, {
// attributes: true,
// childList: true,
// subtree: true
// })
// }
// })
// }
// })
// // 组件卸载时清理
// onUnmounted(() => {
// if (observeResize) {
// window.removeEventListener('resize', debouncedCalculate)
// }
// if (debounceTimer) {
// clearTimeout(debounceTimer)
// }
// resizeObserver?.disconnect()
// mutationObserver?.disconnect()
// })
// // 返回 scroll 对象和刷新函数
// return {
// scroll: tableScroll,
// refreshHeight: debouncedCalculate
// }
// }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
vue
<div ref="tableContainerRef" style="height:calc(100vh - 180px);overflow: hidden; ">
<a-table
:columns="myData.columns"
defaultExpandAllRows
:loading
ref="tableRef"
:key="tableKey"
class="auto-scroll-table"
:scroll="scroll"
:locale="{ emptyText: '未找到符合条件的组织' }"
:dataSource="myData.dataSource"
@expandedRowsChange="handleRowExpanded"
bordered
rowKey="organizationId"
size="small"
:pagination="false"
>
</a-table>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
ts
const handleRowExpanded = (expandedRows: []) => {
nextTick(() => {
recalculate()
})
}
const tableRef = ref()
const tableContainerRef = ref()
const { scroll , recalculate} = useTableAutoHeight(tableRef, tableContainerRef)
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
VN/A |
本站访客数
--次 本站总访问量
--人次