vue实现fullpage
Vue 实现 FullPage 效果
在 Vue 中实现全屏滚动(FullPage)效果可以通过多种方式完成,以下是几种常见的方法:
使用现有库 vue-fullpage.js
安装 vue-fullpage.js 库:
npm install vue-fullpage.js --save
在 Vue 项目中引入并使用:
import Vue from 'vue'
import VueFullPage from 'vue-fullpage.js'
Vue.use(VueFullPage)
在组件中使用:
<template>
<full-page :options="options" ref="fullpage">
<div class="section">第一屏内容</div>
<div class="section">第二屏内容</div>
<div class="section">第三屏内容</div>
</full-page>
</template>
<script>
export default {
data() {
return {
options: {
licenseKey: 'YOUR_KEY',
scrollingSpeed: 700,
navigation: true,
anchors: ['page1', 'page2', 'page3']
}
}
}
}
</script>
<style>
.section {
text-align: center;
font-size: 3em;
color: #fff;
}
</style>
使用原生 CSS 和 JavaScript 实现
通过 CSS 和 JavaScript 可以实现基本的全屏滚动效果:
<template>
<div class="fullpage-container" ref="container">
<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
}
},
mounted() {
window.addEventListener('wheel', this.handleScroll, { passive: false })
this.setSectionHeight()
window.addEventListener('resize', this.setSectionHeight)
},
beforeDestroy() {
window.removeEventListener('wheel', this.handleScroll)
window.removeEventListener('resize', this.setSectionHeight)
},
methods: {
setSectionHeight() {
const height = window.innerHeight + 'px'
document.querySelectorAll('.section').forEach(el => {
el.style.height = height
})
},
handleScroll(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--
}
this.$refs.container.style.transform = `translateY(-${this.currentIndex * 100}vh)`
setTimeout(() => {
this.isScrolling = false
}, 800)
}
}
}
</script>
<style>
.fullpage-container {
transition: transform 0.8s ease;
}
.section {
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
font-size: 2em;
color: #fff;
}
</style>
使用 CSS scroll-snap 属性
现代浏览器支持 CSS scroll-snap 属性,可以轻松实现全屏滚动效果:
<template>
<div class="scroll-container">
<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: '第三屏内容' }
]
}
}
}
</script>
<style>
.scroll-container {
height: 100vh;
overflow-y: scroll;
scroll-snap-type: y mandatory;
}
.section {
height: 100vh;
scroll-snap-align: start;
display: flex;
justify-content: center;
align-items: center;
font-size: 2em;
color: #fff;
}
</style>
注意事项
- 使用第三方库时要注意许可证问题,某些功能可能需要购买许可证
- 移动端触摸事件需要额外处理,确保滑动体验流畅
- 性能优化很重要,特别是当页面内容较多时
- 考虑浏览器兼容性,特别是使用 CSS scroll-snap 时
以上方法可以根据项目需求选择使用,第三方库提供更多功能但增加包体积,原生实现更轻量但需要处理更多细节。







