# VueVirtualScroller
# 常用的几个组件
主要有 RecycleScroller.vue、DynamicScroller.vue和DynamicScrollerItem.vue这三个组件,然而RecycleScroller为实现核心
笔记
RecycleScroller 和 DynamicScroller 两者之间的区别是什么呢?
在应用上 RecycleScroller 需要item的高度为静态的,也就是列表每个item的高度都是一致的。而 DynamicScroller就可以兼容item的高度为动态的。但是理论上 RecycleScroller也可以实现动态高度的item,只要有方案计算到item的height就可以(DynamicScrollerItem解决的就是这个问题)。
# RecycleScroller使用案例
<template>
<RecycleScroller
class="scroller"
:items="list"
:item-size="32"
key-field="id"
v-slot="{ item }">
<div class="user">
{{ item.name }}
</div>
</RecycleScroller>
</template>
<script>
export default {
props: {
list: Array,
}
}
</script>
<style scoped>
.scroller {
height: 100%;
}
.user {
height: 32%;
padding: 0 12px;
display: flex;
align-items: center;
}
</style>
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
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
# DynamicScroller使用案例
<template>
<DynamicScroller
:items="items"
:min-item-size="54"
class="scroller">
<template v-slot="{ item, index, active }">
<DynamicScrollerItem
:item="item"
:active="active"
:size-dependencies="[item.message]"
:data-index="index">
<div class="avatar">
<img
:src="item.avatar"
:key="item.avatar"
alt="avatar"
class="image">
</div>
<div class="text">{{ item.message }}</div>
</DynamicScrollerItem>
</template>
</DynamicScroller>
</template>
<script>
export default {
props: {
items: Array,
},
}
</script>
<style scoped>
.scroller {
height: 100%;
}
</style>
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
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
# 实际使用过程中遇到的问题
# 扩展下拉刷新功能
<template>
<div ref="container" class="dynamic-scroller-container">
<div
class="refresh-wrapper"
@touchstart="handleTouchStart"
@touchmove="handleTouchMove"
@touchend="handleTouchEnd"
@mousedown="handleMouseDown"
@mousemove="handleMouseMove"
@mouseup="handleMouseUp"
@mouseleave="handleMouseUp"
>
<div
ref="refreshIndicator"
class="refresh-indicator"
:style="{ height: refreshDistance + 'px' }"
>
<div v-if="refreshing" class="refresh-text"><v-loading /></div>
<div v-else-if="pullingDown" class="refresh-text">下拉刷新</div>
<div v-else-if="refreshSuccess" class="refresh-text">刷新成功</div>
</div>
<DynamicScroller
v-if="hasData"
:items="list"
:min-item-size="minItemSize"
:key-field="keyField"
class="virtual-scroller"
:style="{ marginTop: computedTopOffset + 'px' }"
@scroll-end="handleScrollEnd"
ref="scroller"
>
<template v-slot="{ item, index, active }">
<DynamicScrollerItem
:item="item"
:active="active"
:size-dependencies="sizeDependencies"
:data-index="index"
class="virtual-scroller-item"
>
<slot
name="item"
:item="item"
:index="index"
@click="handleItemClick(item)"
/>
</DynamicScrollerItem>
</template>
<template #after>
<div :class="afterClass">
<div
v-if="pageOption.end && !hasMoreData"
class="flex-row transition h-50 justify-center items-center text-secondary fs-26 mt-auto"
>
<span>~没有更多了~</span>
</div>
<div
v-else-if="loadingMore"
class="w-full flex-row transition h-50 justify-center items-center text-secondary fs-26 mt-auto"
style="z-index: 10"
>
<v-loading />
</div>
<div v-else class="h-50" />
</div>
</template>
</DynamicScroller>
<!-- 空状态 -->
<div
v-else-if="showEmptyState"
class="flex-row transition justify-center text-secondary fs-26 mt-auto h-full items-center"
>
{{ emptyText }}
</div>
<!-- 初始加载状态 -->
<div
v-else-if="showInitialLoading"
class="flex-row transition h-full justify-center text-secondary fs-26 mt-auto items-center"
>
<v-loading />
</div>
</div>
</div>
</template>
<script>
import lodash from "lodash";
export default {
name: "DynamicScrollerList",
components: {},
props: {
request: {
type: Function,
required: true,
validator: (value) => typeof value === "function",
},
minItemSize: {
type: Number,
default: 100,
validator: (value) => value > 0,
},
keyField: {
type: String,
default: "id",
},
sizeDependencies: {
type: Array,
default: () => [],
},
afterClass: {
type: String,
default: "flex-col",
},
emptyText: {
type: String,
default: "暂无数据",
},
pageSize: {
type: Number,
default: 20,
validator: (value) => value > 0,
},
debounceDelay: {
type: Number,
default: 300,
validator: (value) => value >= 0,
},
// 下拉刷新触发阈值(达到即触发刷新)
pullThreshold: {
type: Number,
default: 60,
validator: (value) => value >= 30,
},
// 最大可下拉距离(视觉上限)
maxPullDistance: {
type: Number,
default: 100,
validator: (value) => value >= 60,
},
// 是否启用下拉刷新
enablePullToRefresh: {
type: Boolean,
default: true,
},
},
data() {
return {
loading: false,
loadingMore: false,
userHasInteracted: false,
refreshing: false,
refreshSuccess: false,
pullingDown: false,
error: null,
pageOption: {
end: false,
curPage: 1,
pageSize: this.pageSize,
},
list: [],
hasMoreData: true,
// 下拉刷新相关数据
startY: 0,
currentY: 0,
refreshDistance: 0,
touchScrollTop: 0,
isTouching: false,
lastMoveY: 0,
// 鼠标事件相关
isMouseDown: false,
};
},
computed: {
hasData() {
return this.list && this.list.length > 0;
},
showEmptyState() {
return (
!this.loading &&
!this.hasData &&
(this.pageOption.end || !this.hasMoreData)
);
},
showInitialLoading() {
return this.loading && !this.hasData;
},
// 列表顶部需要下移的距离:刷新中固定为阈值,其余按实时下拉距离
computedTopOffset() {
if (!this.enablePullToRefresh) return 0;
return this.refreshing ? this.pullThreshold : this.refreshDistance;
},
},
watch: {
pageSize: {
handler(newVal) {
this.pageOption.pageSize = newVal;
},
immediate: true,
},
},
created() {
this.debouncedScrollEnd = lodash.debounce(
this.loadMoreData,
this.debounceDelay
);
},
mounted() {
this.$nextTick(() => {
this.loadInitialData();
});
},
methods: {
// 鼠标事件处理(支持PC端)
handleMouseDown(e) {
if (!this.enablePullToRefresh || this.refreshing) return;
this.startY = e.pageY;
this.lastMoveY = this.startY;
const scrollerRef = this.$refs.scroller;
const scroller = scrollerRef && scrollerRef.$el ? scrollerRef.$el : null;
this.touchScrollTop = scroller ? scroller.scrollTop : 0;
this.isMouseDown = true;
},
handleMouseMove(e) {
if (!this.enablePullToRefresh || !this.isMouseDown || this.refreshing) {
return;
}
const currentY = e.pageY;
const diff = currentY - this.startY;
// 实时读取滚动位置,确保只能在顶部触发
const scrollerRef = this.$refs.scroller;
const scroller = scrollerRef && scrollerRef.$el ? scrollerRef.$el : null;
const currentScrollTop = scroller ? scroller.scrollTop : 0;
// 仅向下拉且在顶部时处理
if (currentScrollTop <= 0 && diff > 0) {
e.preventDefault();
this.pullingDown = true;
this.currentY = currentY;
this.lastMoveY = currentY;
// 阻尼:前半段跟手,后半段递减
const raw = diff;
const damped =
raw < this.pullThreshold
? raw
: this.pullThreshold + (raw - this.pullThreshold) * 0.4;
this.refreshDistance = Math.min(damped, this.maxPullDistance);
} else {
this.pullingDown = false;
this.refreshDistance = 0;
}
},
handleMouseUp() {
if (!this.enablePullToRefresh) return;
this.isMouseDown = false;
// 触发刷新或复位
if (
this.pullingDown &&
this.refreshDistance >= this.pullThreshold &&
!this.refreshing
) {
this.handleRefresh();
} else {
this.refreshDistance = 0;
this.pullingDown = false;
}
},
// 下拉刷新相关方法
handleTouchStart(e) {
if (!this.enablePullToRefresh || this.refreshing) return;
const touch = e.touches && e.touches[0];
if (!touch) return;
this.startY = touch.pageY;
this.lastMoveY = this.startY;
const scrollerRef = this.$refs.scroller;
const scroller = scrollerRef && scrollerRef.$el ? scrollerRef.$el : null;
this.touchScrollTop = scroller ? scroller.scrollTop : 0;
this.isTouching = true;
},
handleTouchMove(e) {
if (!this.enablePullToRefresh || !this.isTouching || this.refreshing) {
return;
}
const touch = e.touches && e.touches[0];
if (!touch) return;
const currentY = touch.pageY;
const diff = currentY - this.startY;
// 实时读取滚动位置,确保只能在顶部触发
const scrollerRef = this.$refs.scroller;
const scroller = scrollerRef && scrollerRef.$el ? scrollerRef.$el : null;
const currentScrollTop = scroller ? scroller.scrollTop : 0;
// 仅向下拉且在顶部时处理
if (currentScrollTop <= 0 && diff > 0) {
// 阻止浏览器原生回弹(仅在可取消时)
if (e.cancelable) e.preventDefault();
this.pullingDown = true;
this.currentY = currentY;
this.lastMoveY = currentY;
// 阻尼:前半段跟手,后半段递减
const raw = diff;
const damped =
raw < this.pullThreshold
? raw
: this.pullThreshold + (raw - this.pullThreshold) * 0.4;
this.refreshDistance = Math.min(damped, this.maxPullDistance);
} else {
this.pullingDown = false;
this.refreshDistance = 0;
}
},
handleTouchEnd() {
if (!this.enablePullToRefresh) return;
this.isTouching = false;
// 触发刷新或复位
if (
this.pullingDown &&
this.refreshDistance >= this.pullThreshold &&
!this.refreshing
) {
this.handleRefresh();
} else {
this.refreshDistance = 0;
this.pullingDown = false;
}
},
/**
* 加载初始数据
*/
async loadInitialData() {
// 优化:即使在end状态下,如果正在刷新也应该加载数据
if (this.pageOption.end && !this.refreshing) {
this.loading = false;
return;
}
await this.fetchData(true);
},
/**
* 加载更多数据
*/
async loadMoreData() {
// 优化:简化条件判断
if (
this.pageOption.end ||
this.loading ||
this.loadingMore ||
!this.hasMoreData
) {
return;
}
this.userHasInteracted = true;
this.loadingMore = true;
await this.fetchData(false);
this.loadingMore = false;
},
/**
* 统一的数据获取方法
* @param {boolean} isInitial - 是否为初始加载
*/
async fetchData(isInitial = false) {
try {
this.loading = true;
this.error = null;
const requestParams = {
curPage: isInitial ? 1 : this.pageOption.curPage,
pageSize: this.pageOption.pageSize,
};
const response = await this.request(requestParams);
if (!response || typeof response !== "object") {
throw new Error("Invalid response format");
}
const { data = {} } = response;
const { records = [] } = data;
// 处理数据
if (isInitial || this.refreshing) {
this.list = records;
} else {
this.list = [...this.list, ...records];
}
// 更新分页状态
this.updatePageState(records.length);
} catch (error) {
this.handleError(error);
} finally {
this.loading = false;
// 刷新结束的可视状态交由 handleRefresh 收尾
}
},
/**
* 更新分页状态
* @param {number} recordCount - 当前页记录数
*/
updatePageState(recordCount) {
// 修复分页逻辑:只有当返回记录数小于页面大小时才标记为结束
if (recordCount < this.pageOption.pageSize) {
this.pageOption.end = true;
this.hasMoreData = false;
} else {
this.pageOption.curPage += 1;
this.hasMoreData = true;
}
},
/**
* 错误处理
* @param {Error} error - 错误对象
*/
handleError(error) {
console.error("获取数据失败:", error);
this.error = error.message || "数据加载失败";
// 不要直接设置end为true,除非确认没有更多数据
// this.pageOption.end = true;
// 触发错误事件
this.$emit("error", {
error,
message: this.error,
});
},
/**
* 滚动到底部处理函数
*/
handleScrollEnd() {
this.userHasInteracted = true;
this.debouncedScrollEnd();
},
/**
* 处理项目点击
* @param {Object} data - 项目数据
*/
handleItemClick(data) {
this.$emit("itemClick", data);
},
/**
* 重置组件状态
*/
resetState() {
this.pageOption = {
end: false,
curPage: 1,
pageSize: this.pageSize,
};
this.list = [];
this.error = null;
this.hasMoreData = true;
this.userHasInteracted = false;
},
/**
* 刷新数据
*/
async refresh() {
// 重置分页状态
this.pageOption = {
end: false,
curPage: 1,
pageSize: this.pageSize,
};
this.error = null;
this.hasMoreData = true;
await this.fetchData(true);
},
/**
* 下拉刷新处理函数
*/
async handleRefresh() {
this.refreshing = true;
this.refreshSuccess = false;
try {
// 固定指示器在阈值高度
this.refreshDistance = this.pullThreshold;
await this.refresh();
this.$emit("refresh");
this.refreshSuccess = true;
// 显示刷新成功状态一小段时间
setTimeout(() => {
this.refreshSuccess = false;
}, 500);
} finally {
this.refreshing = false;
this.pullingDown = false;
// 轻微延迟复位,避免抖动
setTimeout(() => {
this.refreshDistance = 0;
}, 500);
}
},
/**
* 手动触发加载更多
*/
async loadMore() {
await this.loadMoreData();
},
/**
* 重新加载数据
*/
async reload() {
this.resetState();
await this.loadInitialData();
},
},
};
</script>
<style lang="less" scoped>
.dynamic-scroller-container {
height: 100%;
width: 100%;
position: relative;
}
.refresh-wrapper {
height: 100%;
width: 100%;
position: relative;
// 添加鼠标事件相关样式
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.refresh-indicator {
position: absolute;
top: 0;
left: 0;
width: 100%;
display: flex;
justify-content: center;
align-items: center;
overflow: hidden;
transform: translateY(-100%);
// transition: height 0.2s ease-out;
}
.refresh-text {
font-size: 26px;
color: #999;
}
.virtual-scroller {
/* 开启硬件加速 */
-webkit-overflow-scrolling: touch;
/* 禁用回弹效果 */
overscroll-behavior: none;
height: 100%;
width: 100%;
}
.virtual-scroller-item {
/* 确保项目正确渲染 */
contain: layout style paint;
}
/* 优化滚动性能 */
.virtual-scroller::-webkit-scrollbar {
width: 0;
background: transparent;
}
/* 加载状态样式优化 */
.transition {
transition: opacity 0.3s ease;
}
/* 空状态样式 */
.transition:has(span) {
opacity: 0.8;
}
</style>
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
# 如何在元素间实现间隔
1.通过样式边距
<RecycleScroller
:item-style="() => ({ marginBottom: '10px' })"
/>
1
2
3
2
3
2.添加额外元素
<template>
// ... existing code ..
<div class="pb-20 box-border h-full">
<DynamicScrollerList
class="h-full mx-30 rounded-8 bc-white overflow-y-auto"
afterClass="bc-grey mt-10"
:request="getList"
>
<template #item="{ item }">
<div class="px-30 py-20 flex-col fs-26">
{{ item.content }}
</div>
<div class="border-b mx-30"></div>
</template>
</DynamicScrollerList>
</div>
// ... existing code ...
</template>
// ... existing code ...
<style lang="less" scoped>
::v-deep .vue-recycle-scroller__item-wrapper > *:last-child {
.border-b {
border: none;
}
}
</style>
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
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