vue滚动实现换页
在Vue中实现滚动换页效果,可以通过监听滚动事件并结合计算属性来实现。以下是一个基本的实现方案:
-
首先,在模板中设置容器和页面内容:

<template> <div class="scroll-container" @scroll.passive="handleScroll"> <div class="page" v-for="(page, index) in pages" :key="index"> {{ page.content }} </div> </div> </template> -
在script部分实现滚动逻辑:
<script> export default { data() { return { pages: [ { content: '页面1内容' }, { content: '页面2内容' }, { content: '页面3内容' } ], currentPage: 0, scrolling: false } }, methods: { handleScroll(event) { if (this.scrolling) return; const container = event.target; const scrollTop = container.scrollTop; const containerHeight = container.clientHeight; // 向下滚动 if (scrollTop > (this.currentPage + 1) * containerHeight - containerHeight / 2) { this.scrollToPage(this.currentPage + 1); } // 向上滚动 else if (scrollTop < this.currentPage * containerHeight - containerHeight / 2) { this.scrollToPage(this.currentPage - 1); } }, scrollToPage(page) { if (page < 0 || page >= this.pages.length) return; this.scrolling = true; this.currentPage = page; const container = this.$el.querySelector('.scroll-container'); container.scrollTo({ top: page * container.clientHeight, behavior: 'smooth' }); setTimeout(() => { this.scrolling = false; }, 500); } } } </script> -
添加样式:

<style> .scroll-container { height: 100vh; overflow-y: auto; scroll-snap-type: y mandatory; }
.page { height: 100vh; scroll-snap-align: start; }
```这个实现方案结合了以下关键技术点:
- 使用
scroll-snap-type和scroll-snap-align实现吸附效果 - 监听滚动事件判断滚动方向
- 平滑滚动到目标页面
- 防抖处理防止多次触发
你可以根据需要调整滚动灵敏度、动画效果等参数来优化用户体验。






