vue实现全屏上下滚动
实现全屏上下滚动效果
在Vue中实现全屏上下滚动效果,可以通过监听鼠标滚轮事件或触摸事件来控制页面切换。以下是两种常见实现方式:
使用CSS和Vue指令实现
通过CSS设置全屏容器,结合Vue指令监听滚动事件:
<template>
<div class="fullscreen-scroll" v-wheel="handleWheel">
<div class="section" v-for="(item, index) in sections" :key="index">
{{ item.content }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
sections: [
{ content: '第一屏内容' },
{ content: '第二屏内容' },
{ content: '第三屏内容' }
],
currentIndex: 0,
isScrolling: false
}
},
directives: {
wheel: {
inserted(el, binding) {
el.addEventListener('wheel', binding.value)
},
unbind(el, binding) {
el.removeEventListener('wheel', binding.value)
}
}
},
methods: {
handleWheel(e) {
if (this.isScrolling) return
this.isScrolling = true
if (e.deltaY > 0 && this.currentIndex < this.sections.length - 1) {
this.currentIndex++
} else if (e.deltaY < 0 && this.currentIndex > 0) {
this.currentIndex--
}
window.scrollTo({
top: window.innerHeight * this.currentIndex,
behavior: 'smooth'
})
setTimeout(() => {
this.isScrolling = false
}, 800)
}
}
}
</script>
<style>
.fullscreen-scroll {
height: 100vh;
overflow: hidden;
}
.section {
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
font-size: 2rem;
}
</style>
使用第三方库实现
对于更复杂的需求,可以使用专门的全屏滚动库如vue-fullpage.js:

-
安装依赖:
npm install vue-fullpage.js -
在Vue项目中使用:

<template> <full-page :options="options" ref="fullpage"> <div class="section">第一屏内容</div> <div class="section">第二屏内容</div> <div class="section">第三屏内容</div> </full-page> </template>
export default { components: { 'full-page': VueFullPage }, data() { return { options: { menu: '#menu', anchors: ['page1', 'page2', 'page3'], sectionsColor: ['#41b883', '#ff5f45', '#0798ec'], navigation: true, scrollBar: false } } } }
.section { text-align: center; font-size: 3em; } ```移动端触摸支持
对于移动设备,需要添加触摸事件支持:
methods: {
handleTouchStart(e) {
this.startY = e.touches[0].clientY
},
handleTouchEnd(e) {
const endY = e.changedTouches[0].clientY
const diff = this.startY - endY
if (Math.abs(diff) < 50) return
if (diff > 0 && this.currentIndex < this.sections.length - 1) {
this.currentIndex++
} else if (diff < 0 && this.currentIndex > 0) {
this.currentIndex--
}
window.scrollTo({
top: window.innerHeight * this.currentIndex,
behavior: 'smooth'
})
}
}
在模板中添加相应的事件监听:
<div
class="fullscreen-scroll"
v-wheel="handleWheel"
@touchstart="handleTouchStart"
@touchend="handleTouchEnd"
>
性能优化建议
- 使用
requestAnimationFrame替代setTimeout实现更流畅的动画 - 添加防抖机制避免快速滚动导致的多次触发
- 对于内容较多的页面,考虑使用懒加载技术
- 在CSS中使用
will-change: transform提升动画性能
以上方法可以根据项目需求选择使用,第三方库方案通常更全面但会增加包体积,原生实现则更轻量但需要自行处理更多细节。






