vue实现全屏滚动
实现全屏滚动的 Vue 方法
使用第三方库 vue-fullpage.js
安装 vue-fullpage.js:
npm install vue-fullpage.js
在 Vue 项目中引入并注册:
import Vue from 'vue'
import fullpage from 'vue-fullpage.js'
Vue.use(fullpage)
在模板中使用:
<template>
<full-page :options="options">
<div class="section">第一屏内容</div>
<div class="section">第二屏内容</div>
<div class="section">第三屏内容</div>
</full-page>
</template>
<script>
export default {
data() {
return {
options: {
navigation: true,
scrollBar: true
}
}
}
}
</script>
自定义实现全屏滚动
监听鼠标滚轮事件,结合 CSS 实现全屏滚动效果:
// 在 mounted 钩子中添加事件监听
mounted() {
window.addEventListener('wheel', this.handleScroll, { passive: false })
},
methods: {
handleScroll(e) {
e.preventDefault()
const delta = e.deltaY
const currentSection = this.currentSectionIndex
const totalSections = this.sections.length
if (delta > 0 && currentSection < totalSections - 1) {
this.scrollToSection(currentSection + 1)
} else if (delta < 0 && currentSection > 0) {
this.scrollToSection(currentSection - 1)
}
},
scrollToSection(index) {
this.currentSectionIndex = index
window.scrollTo({
top: window.innerHeight * index,
behavior: 'smooth'
})
}
}
CSS 关键样式
确保每个 section 占据整个视口:
.section {
height: 100vh;
width: 100%;
overflow: hidden;
}
移动端触摸支持
添加 touch 事件处理:
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) {
if (diff > 0) {
this.scrollToSection(this.currentSectionIndex + 1)
} else {
this.scrollToSection(this.currentSectionIndex - 1)
}
}
}
}
性能优化建议
使用 CSS will-change 属性提升滚动性能:
.section {
will-change: transform;
}
考虑使用 requestAnimationFrame 优化滚动动画:
function smoothScroll(targetY) {
const startY = window.pageYOffset
const distance = targetY - startY
const duration = 1000
let start = null
function step(timestamp) {
if (!start) start = timestamp
const progress = timestamp - start
const percent = Math.min(progress / duration, 1)
window.scrollTo(0, startY + distance * percent)
if (progress < duration) {
window.requestAnimationFrame(step)
}
}
window.requestAnimationFrame(step)
}






