Skip to content

Commit

Permalink
feat(useWindowScroll): Add computed for scrolling
Browse files Browse the repository at this point in the history
  • Loading branch information
chensiyuan committed Oct 25, 2023
1 parent 6541a6f commit 2d15313
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 7 deletions.
8 changes: 7 additions & 1 deletion packages/core/useWindowScroll/demo.vue
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<script setup lang="ts">
import { useWindowScroll } from '@vueuse/core'
const { x, y } = useWindowScroll()
const { x, y } = useWindowScroll({ behavior: 'smooth' })
</script>

<template>
Expand All @@ -18,6 +18,12 @@ const { x, y } = useWindowScroll()
y: {{ y }}
</div>
</div>
<button @click="x += 200">
scroll X
</button>
<button @click="y += 200">
scroll Y
</button>
</template>

<style scoped>
Expand Down
2 changes: 2 additions & 0 deletions packages/core/useWindowScroll/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,6 @@ Reactive window scroll
import { useWindowScroll } from '@vueuse/core'

const { x, y } = useWindowScroll()
x.value = 100
y.value = 100
```
33 changes: 27 additions & 6 deletions packages/core/useWindowScroll/index.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,52 @@
import { ref } from 'vue-demi'
import { computed, ref } from 'vue-demi'
import { useEventListener } from '../useEventListener'
import type { ConfigurableWindow } from '../_configurable'
import { defaultWindow } from '../_configurable'

export interface UseWindowScrollOptions extends ConfigurableWindow {
behavior?: ScrollBehavior
}

/**
* Reactive window scroll.
*
* @see https://vueuse.org/useWindowScroll
* @param options
*/
export function useWindowScroll({ window = defaultWindow }: ConfigurableWindow = {}) {
export function useWindowScroll({ window = defaultWindow, behavior = 'auto' }: UseWindowScrollOptions = {}) {
if (!window) {
return {
x: ref(0),
y: ref(0),
}
}

const x = ref(window.scrollX)
const y = ref(window.scrollY)
const internalX = ref(window.scrollX)
const internalY = ref(window.scrollY)

const x = computed({
get() {
return internalX.value
},
set(x: number) {
scrollTo({ left: x, behavior })
},
})
const y = computed({
get() {
return internalY.value
},
set(y: number) {
scrollTo({ top: y, behavior })
},
})

useEventListener(
window,
'scroll',
() => {
x.value = window.scrollX
y.value = window.scrollY
internalX.value = window.scrollX
internalY.value = window.scrollY
},
{
capture: false,
Expand Down

0 comments on commit 2d15313

Please sign in to comment.