Skip to content

Commit c600d1b

Browse files
author
lmhcoding
committed
feat(useWindowScroll): support throttle
1 parent 3ccabbf commit c600d1b

File tree

1 file changed

+26
-10
lines changed

1 file changed

+26
-10
lines changed

src/useWindowScroll.ts

+26-10
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,30 @@
1-
import { reactive, toRefs } from 'vue'
1+
import { ref, readonly, DeepReadonly, Ref } from 'vue'
22
import { useEvent } from './useEvent'
3+
import { throttle } from 'throttle-debounce'
34

4-
export function useWindowScroll() {
5-
const state = reactive({
6-
x: 0,
7-
y: 0
8-
})
9-
useEvent('scroll', () => {
10-
state.x = window.scrollX
11-
state.y = window.scrollY
5+
export interface IWindowScrollState {
6+
x: DeepReadonly<Ref<number>>
7+
y: DeepReadonly<Ref<number>>
8+
clear: () => void
9+
}
10+
11+
export function useWindowScroll(delay = 200): IWindowScrollState {
12+
const x = ref(0)
13+
const y = ref(0)
14+
let cb = () => {
15+
x.value = window.scrollX
16+
y.value = window.scrollY
17+
}
18+
if (delay) {
19+
cb = throttle(delay, cb)
20+
}
21+
const [, clear] = useEvent('scroll', cb, {
22+
passive: true,
23+
capture: false
1224
})
13-
return toRefs(state)
25+
return {
26+
x: readonly(x),
27+
y: readonly(y),
28+
clear
29+
}
1430
}

0 commit comments

Comments
 (0)