Vue开发之Vue3项目实现页面上下滑动

36人浏览 / 0人评论 / 添加收藏

在Vue3的项目中,发现页面高度超过一定程度,无法通过鼠标或者触控板实现上下滑动。

那如何在Vue3项目中实现页面上下滑动呢?


 

在Vue 3中实现页面上下滑动,通常涉及到监听滚动事件并相应地更新组件的状态或样式。以下是一些实现页面上下滑动的基本方法:

方法1:使用window对象的滚动事件
你可以在Vue组件的mounted钩子中添加一个事件监听器来监听滚动事件,并在beforeUnmount钩子中移除它,以避免内存泄漏。

以下是具体实现的方法:

<template>
 <div class="scroll-container" @scroll="handleScroll">
   <!-- 你的内容 -->
 </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';

const scrollPosition = ref(0);

function handleScroll(event) {
 scrollPosition.value = event.target.scrollTop;
}

onMounted(() => {
 window.addEventListener('scroll', handleScroll);
});

onBeforeUnmount(() => {
 window.removeEventListener('scroll', handleScroll);
});
</script>

<style>
.scroll-container {
 height: 800px; /* 或其他固定高度 */
 overflow-y: auto; /* 启用垂直滚动 */
}
</style>

以上代码经过实测可行,希望可以帮助到你。

 

全部评论