feat: use vueuse to lock scrolling

This commit is contained in:
kolaente 2022-03-22 22:48:32 +01:00 committed by Gitea
parent 574ecff12d
commit f9b7e2fd76

View file

@ -8,6 +8,7 @@
{ 'has-overflow': overflow }, { 'has-overflow': overflow },
variant, variant,
]" ]"
ref="modal"
> >
<div <div
class="modal-container" class="modal-container"
@ -62,7 +63,8 @@
<script lang="ts" setup> <script lang="ts" setup>
import BaseButton from '@/components/base/BaseButton.vue' import BaseButton from '@/components/base/BaseButton.vue'
import {onUnmounted, watch} from 'vue' import {ref, watch} from 'vue'
import {useScrollLock} from '@vueuse/core'
const props = withDefaults(defineProps<{ const props = withDefaults(defineProps<{
enabled?: boolean, enabled?: boolean,
@ -78,32 +80,18 @@ const props = withDefaults(defineProps<{
defineEmits(['close', 'submit']) defineEmits(['close', 'submit'])
// Based on https://css-tricks.com/prevent-page-scrolling-when-a-modal-is-open/ const modal = ref<HTMLElement | null>(null)
function resetScrolling() { const scrollLock = useScrollLock(modal)
const body = document.body
const scrollY = body.style.top
body.style.position = ''
body.style.top = ''
window.scrollTo(0, parseInt(scrollY || '0') * -1)
}
watch( watch(
() => props.enabled, () => props.enabled,
enabled => { enabled => {
if (enabled) { scrollLock.value = enabled
const scrollY = window.scrollY
document.body.style.position = 'fixed'
document.body.style.top = `-${scrollY}px`
} else {
resetScrolling()
}
}, },
{ {
immediate: true, immediate: true,
}, },
) )
onUnmounted(resetScrolling)
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>