我需要帮助弄清楚如何在 vue easy lightbox 打开时禁用滚动。我尝试过的任何方法都不起作用。
溢出:隐藏不起作用 我尝试添加 :scrollDisabled="true" 。还是没有运气
我问过chatgpt,它建议在灯箱上创建一个观察者,但这也不起作用。
任何帮助将不胜感激
<template>
<div class="container">
<button @click="toggleScrollLock">
{{ isScrollLocked ? 'Unlock Scroll' : 'Lock Scroll' }}
</button>
<p>Scroll down to test. When locked, the page shouldn’t scroll.</p>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
const isScrollLocked = ref(false)
function toggleScrollLock() {
isScrollLocked.value = !isScrollLocked.value
if (isScrollLocked.value) {
document.body.style.overflow = 'hidden'
} else {
document.body.style.overflow = ''
}
}
</script>
<style scoped>
.container {
/* Make the page tall so we can easily see scroll locking. */
height: 2000px;
background-color: #fafafa;
padding: 20px;
font-family: sans-serif;
}
button {
margin: 20px;
padding: 10px 15px;
cursor: pointer;
}
</style>
所以CSS和toggleScroll函数隐藏滚动起作用,这似乎是Vue的问题。
我不知道你的设置是什么,我对 Vue 也不是很熟悉,但是,像下面这样重构代码可以按预期工作,所以你可以检查一下你的函数是否正在破坏,你的函数中是否收到任何警告/错误安慰 ?您使用他们的 CLI 吗?
const {
createApp,
ref
} = Vue
createApp({
data: () => ({
isScrollLocked: ref(false),
}),
methods: {
toggleScrollLock() {
console.log(this.isScrollLocked)
this.isScrollLocked = !this.isScrollLocked
if (this.isScrollLocked) {
document.body.style.overflow = "hidden"
} else {
document.body.style.overflow = ""
}
},
},
}).mount("#app")
.container {
/* Make the page tall so we can easily see scroll locking. */
height: 2000px;
background-color: #fafafa;
padding: 20px;
font-family: sans-serif;
}
button {
margin: 20px;
padding: 10px 15px;
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/3.5.4/vue.global.min.js"></script>
<div id="app" class="container">
<div class="container">
<button @click="toggleScrollLock">
{{ isScrollLocked ? 'Unlock Scroll' : 'Lock Scroll' }}
</button>
<p>Scroll down to test. When locked, the page shouldn’t scroll.</p>
</div>
</div>