Open History to see the last commit
1<template>
2 <div>
3 <p>
4 This smooth scroll example uses the <code>`scrollToFn`</code> to implement
5 a custom scrolling function for the methods like
6 <code>`scrollToIndex`</code> and <code>`scrollToOffset`</code>
7 </p>
8β
9 <br />
10 <br />
11β
12 <div>
13 <button
14 @click="
15 (rowVirtualizer.scrollToIndex(randomIndex),
16 (randomIndex = generateRandomIndex()))
17 "
18 >
19 Scroll To Random Index ({{ randomIndex }})
20 </button>
21 </div>
22β
23 <br />
24 <br />
25β
26 <div
27 ref="parentRef"
28 class="List"
29 :style="{
30 height: `200px`,
31 width: `400px`,
32 overflow: 'auto',
33 }"
34 >
35 <div
36 :style="{
37 height: `${totalSize}px`,
38 width: '100%',
39 position: 'relative',
40 }"
41 >
42 <div
43 v-for="virtualRow in virtualRows"
44 :key="virtualRow.key"
45 :class="virtualRow.index % 2 ? 'ListItemOdd' : 'ListItemEven'"
46 :style="{
47 position: 'absolute',
48 top: 0,
49 left: 0,
50 width: '100%',
51 height: `${virtualRow.size}px`,
52 transform: `translateY(${virtualRow.start}px)`,
53 }"
54 >
55 Row {{ virtualRow.index }}
56 </div>
57 </div>
58 </div>
59 </div>
60</template>
61β
62<script setup lang="ts">
63import { ref, computed } from 'vue'
64import {
65 elementScroll,
66 useVirtualizer,
67 VirtualizerOptions,
68} from '@tanstack/vue-virtual'
69β
70const easeInOutQuint = (t: number) => {
71 return t < 0.5 ? 16 * t * t * t * t * t : 1 + 16 * --t * t * t * t * t
72}
73β
74const generateRandomIndex = () => Math.floor(Math.random() * 10000)
75β
76const randomIndex = ref(generateRandomIndex())
77β
78const parentRef = ref<HTMLElement | null>(null)
79const scrollingRef = ref<number>()
80β
81const scrollToFn: VirtualizerOptions<any, any>['scrollToFn'] = (
82 offset,
83 canSmooth,
84 instance,
85) => {
86 const duration = 1000
87 const start = parentRef.value?.scrollTop || 0
88 const startTime = (scrollingRef.value = Date.now())
89β
90 const run = () => {
91 if (scrollingRef.value !== startTime) return
92 const now = Date.now()
93 const elapsed = now - startTime
94 const progress = easeInOutQuint(Math.min(elapsed / duration, 1))
95 const interpolated = start + (offset - start) * progress
96β
97 if (elapsed < duration) {
98 elementScroll(interpolated, canSmooth, instance)
99 requestAnimationFrame(run)
100 } else {
101 elementScroll(interpolated, canSmooth, instance)
102 }
103 }
104β
105 requestAnimationFrame(run)
106}
107β
108const rowVirtualizerOptions = computed(() => {
109 return {
110 count: 10000,
111 getScrollElement: () => parentRef.value,
112 estimateSize: () => 35,
113 overscan: 5,
114 scrollToFn,
115 }
116})
117β
118const rowVirtualizer = useVirtualizer(rowVirtualizerOptions)
119β
120const virtualRows = computed(() => rowVirtualizer.value.getVirtualItems())
121β
122const totalSize = computed(() => rowVirtualizer.value.getTotalSize())
123</script>