/
index.ts
75 lines (68 loc) · 1.84 KB
/
index.ts
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
import type { UnwrapNestedRefs } from 'vue-demi'
import { nextTick, reactive, unref, watch } from 'vue-demi'
import type { MaybeRef } from '@vueuse/shared'
import type { UseScrollOptions } from '../useScroll'
import { useScroll } from '../useScroll'
export interface UseInfiniteScrollOptions extends UseScrollOptions {
/**
* The minimum distance between the bottom of the element and the bottom of the viewport
*
* @default 0
*/
distance?: number
/**
* The direction in which to listen the scroll.
*
* @default 'bottom'
*/
direction?: 'top' | 'bottom'
/**
* Whether to preserve the current scroll position when loading more items.
*
* @default false
*/
preserveScrollPosition?: boolean
}
/**
* Reactive infinite scroll.
*
* @see https://vueuse.org/useInfiniteScroll
*/
export function useInfiniteScroll(
element: MaybeRef<HTMLElement | SVGElement | Window | Document | null | undefined>,
onLoadMore: (state: UnwrapNestedRefs<ReturnType<typeof useScroll>>) => void | Promise<void>,
options: UseInfiniteScrollOptions = {},
) {
const direction = options.direction ?? 'bottom'
const state = reactive(useScroll(
element,
{
...options,
offset: {
[direction]: options.distance ?? 0,
...options.offset,
},
},
))
watch(
() => state.arrivedState[direction],
async(v) => {
if (v) {
const elem = unref(element) as Element
const previous = {
height: elem?.scrollHeight ?? 0,
width: elem?.scrollWidth ?? 0,
}
await onLoadMore(state)
if (options.preserveScrollPosition && elem) {
nextTick(() => {
elem.scrollTo({
top: elem.scrollHeight - previous.height,
left: elem.scrollWidth - previous.width,
})
})
}
}
},
)
}