vue实现全屏滚动
Vue实现全屏滚动的方法
全屏滚动效果可以通过多种方式实现,以下是几种常见的Vue实现方法:
使用第三方库vue-fullpage.js
安装vue-fullpage.js库:
npm install vue-fullpage.js
在Vue项目中引入并使用:
import Vue from 'vue'
import vueFullpage from 'vue-fullpage.js'
Vue.use(vueFullpage)
模板中使用:
<template>
<full-page ref="fullpage" :options="options">
<div class="section">第一屏内容</div>
<div class="section">第二屏内容</div>
<div class="section">第三屏内容</div>
</full-page>
</template>
<script>
export default {
data() {
return {
options: {
licenseKey: 'YOUR_KEY_HERE',
afterLoad: this.afterLoad,
scrollOverflow: true,
scrollBar: false,
menu: '#menu',
navigation: true,
anchors: ['page1', 'page2', 'page3'],
sectionsColor: ['#41b883', '#ff5f45', '#0798ec']
}
}
},
methods: {
afterLoad(origin, destination) {
console.log('当前屏:', destination.index)
}
}
}
</script>
使用原生CSS和Vue实现
通过CSS的视口单位和Vue的滚动监听实现:
<template>
<div class="fullpage-container" @wheel="handleWheel">
<div
v-for="(item, index) in pages"
:key="index"
class="page"
:style="{ transform: `translateY(${-currentIndex * 100}vh)` }"
>
{{ item.content }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
currentIndex: 0,
pages: [
{ content: '第一屏' },
{ content: '第二屏' },
{ content: '第三屏' }
],
scrolling: false
}
},
methods: {
handleWheel(e) {
if (this.scrolling) return
this.scrolling = true
if (e.deltaY > 0 && this.currentIndex < this.pages.length - 1) {
this.currentIndex++
} else if (e.deltaY < 0 && this.currentIndex > 0) {
this.currentIndex--
}
setTimeout(() => {
this.scrolling = false
}, 1000)
}
}
}
</script>
<style>
.fullpage-container {
height: 100vh;
overflow: hidden;
position: relative;
}
.page {
height: 100vh;
width: 100%;
position: absolute;
transition: transform 0.8s ease;
}
</style>
使用Vue和GSAP实现动画效果
结合GSAP实现平滑的全屏滚动动画:
npm install gsap
实现代码:
import { gsap } from 'gsap'
export default {
data() {
return {
currentSection: 0,
sections: 3,
isAnimating: false
}
},
mounted() {
window.addEventListener('wheel', this.handleScroll)
},
beforeDestroy() {
window.removeEventListener('wheel', this.handleScroll)
},
methods: {
handleScroll(e) {
if (this.isAnimating) return
if (e.deltaY > 0 && this.currentSection < this.sections - 1) {
this.goToSection(this.currentSection + 1)
} else if (e.deltaY < 0 && this.currentSection > 0) {
this.goToSection(this.currentSection - 1)
}
},
goToSection(index) {
this.isAnimating = true
this.currentSection = index
gsap.to(window, {
scrollTo: { y: `${index * window.innerHeight}`, autoKill: false },
duration: 1,
ease: 'power2.inOut',
onComplete: () => {
this.isAnimating = false
}
})
}
}
}
响应式设计注意事项
为确保全屏滚动在不同设备上正常工作,需要添加响应式处理:
@media (max-width: 768px) {
.page {
height: auto;
min-height: 100vh;
}
.fullpage-container {
overflow-y: auto;
}
}
性能优化建议
- 使用
will-change属性提升动画性能 - 对复杂内容进行懒加载
- 限制滚动事件的触发频率
- 使用CSS硬件加速
.page {
will-change: transform;
backface-visibility: hidden;
transform: translateZ(0);
}
以上方法可以根据项目需求选择使用,第三方库提供更多功能但增加包体积,原生实现更轻量但需要手动处理更多细节。







