Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(useWindowScroll): allow rewriting back to scroll #3500

Merged
merged 4 commits into from Nov 9, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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()
x.value = 100
y.value = 100
antfu marked this conversation as resolved.
Show resolved Hide resolved
```
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