Skip to content

Commit

Permalink
feat(useWindowScroll): allow rewriting back to scroll (#3500)
Browse files Browse the repository at this point in the history
Co-authored-by: chensiyuan <250758092@qq.com>
Co-authored-by: Anthony Fu <anthonyfu117@hotmail.com>
  • Loading branch information
3 people committed Nov 9, 2023
1 parent 892666b commit 931b279
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 8 deletions.
8 changes: 7 additions & 1 deletion packages/core/useWindowScroll/demo.vue
@@ -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
Expand Up @@ -12,4 +12,6 @@ Reactive window scroll
import { useWindowScroll } from '@vueuse/core'

const { x, y } = useWindowScroll()
console.log(x.value) // read current x scroll value
y.value = 100 // scroll y to 100
```
36 changes: 29 additions & 7 deletions packages/core/useWindowScroll/index.ts
@@ -1,32 +1,54 @@
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(options: ConfigurableWindow = {}) {
const { window = defaultWindow } = options

export function useWindowScroll(options: UseWindowScrollOptions = {}) {
const { window = defaultWindow, behavior = 'auto' } = options
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 931b279

Please sign in to comment.