Skip to content

Commit

Permalink
feat(useScroll): support throttle
Browse files Browse the repository at this point in the history
  • Loading branch information
lmhcoding committed Sep 30, 2020
1 parent c600d1b commit cc8d636
Showing 1 changed file with 12 additions and 12 deletions.
24 changes: 12 additions & 12 deletions src/useScroll.ts
@@ -1,21 +1,21 @@
import { DeepReadonly, readonly, ref, Ref } from 'vue'
import { useEvent } from './useEvent'
import { throttle } from 'throttle-debounce'

export type IScrollResult = [DeepReadonly<Ref<number>>, DeepReadonly<Ref<number>>, () => void]

export function useScroll(target: string | Element | Ref<Element | null>): IScrollResult {
export function useScroll(target: string | Element | Ref<Element | null>, delay = 200): IScrollResult {
const x = ref(0)
const y = ref(0)
const [eventTarget, clear] = useEvent(
'scroll',
() => {
if (eventTarget.value) {
x.value = ((eventTarget.value as unknown) as Element).scrollLeft
y.value = ((eventTarget.value as unknown) as Element).scrollTop
}
},
{ capture: false, passive: true },
target
)
let cb = () => {
if (eventTarget.value) {
x.value = ((eventTarget.value as unknown) as Element).scrollLeft
y.value = ((eventTarget.value as unknown) as Element).scrollTop
}
}
if (delay) {
cb = throttle(delay, cb)
}
const [eventTarget, clear] = useEvent('scroll', cb, { capture: false, passive: true }, target)
return [readonly(x), readonly(y), clear]
}

0 comments on commit cc8d636

Please sign in to comment.