vue实现页面全屏滚动
Vue 实现页面全屏滚动
使用 vue-fullpage.js 插件
安装 vue-fullpage.js 插件,这是一个专为 Vue 设计的全屏滚动解决方案。通过 npm 或 yarn 安装:
npm install vue-fullpage.js
在 Vue 项目中引入并注册插件:
import Vue from 'vue'
import VueFullPage from 'vue-fullpage.js'
Vue.use(VueFullPage)
在模板中使用全屏滚动组件:
<template>
<full-page :options="options">
<div class="section">第一屏内容</div>
<div class="section">第二屏内容</div>
<div class="section">第三屏内容</div>
</full-page>
</template>
配置选项对象:
export default {
data() {
return {
options: {
licenseKey: 'YOUR_KEY',
scrollingSpeed: 700,
navigation: true,
anchors: ['page1', 'page2', 'page3']
}
}
}
}
使用原生 CSS 和 Vue 实现
通过 CSS 的 scroll-snap 属性和 Vue 的动态绑定实现基础全屏滚动效果。创建全屏容器:
<template>
<div class="fullpage-container">
<div
v-for="(section, index) in sections"
:key="index"
class="section"
>
{{ section.content }}
</div>
</div>
</template>
添加 CSS 样式:
.fullpage-container {
height: 100vh;
overflow-y: scroll;
scroll-snap-type: y mandatory;
}
.section {
height: 100vh;
scroll-snap-align: start;
}
自定义滚动逻辑
通过监听滚动事件和 Vue 的响应式特性实现自定义滚动效果。添加滚动事件监听:
export default {
mounted() {
window.addEventListener('wheel', this.handleScroll, { passive: false })
},
beforeDestroy() {
window.removeEventListener('wheel', this.handleScroll)
},
methods: {
handleScroll(e) {
if (e.deltaY > 0) {
this.scrollToNext()
} else {
this.scrollToPrev()
}
e.preventDefault()
}
}
}
实现滚动方法:
methods: {
scrollToNext() {
const current = this.currentIndex
if (current < this.sections.length - 1) {
this.currentIndex++
this.$refs.container.scrollTo({
top: window.innerHeight * this.currentIndex,
behavior: 'smooth'
})
}
},
scrollToPrev() {
const current = this.currentIndex
if (current > 0) {
this.currentIndex--
this.$refs.container.scrollTo({
top: window.innerHeight * this.currentIndex,
behavior: 'smooth'
})
}
}
}
移动端适配
针对移动设备添加触摸事件支持:
mounted() {
this.$refs.container.addEventListener('touchstart', this.handleTouchStart)
this.$refs.container.addEventListener('touchend', this.handleTouchEnd)
},
methods: {
handleTouchStart(e) {
this.startY = e.touches[0].clientY
},
handleTouchEnd(e) {
const endY = e.changedTouches[0].clientY
if (this.startY - endY > 50) {
this.scrollToNext()
} else if (endY - this.startY > 50) {
this.scrollToPrev()
}
}
}
性能优化
使用 Vue 的 keep-alive 缓存不活跃的页面组件:
<template>
<div class="fullpage-container">
<keep-alive>
<component
:is="currentComponent"
:key="currentIndex"
/>
</keep-alive>
</div>
</template>
添加懒加载功能,延迟加载非当前可见部分的内容:
computed: {
currentComponent() {
return () => import(`@/components/Section${this.currentIndex + 1}`)
}
}






