vue实现全屏上下滚动
实现全屏上下滚动效果
在Vue中实现全屏上下滚动效果,可以通过监听鼠标滚轮事件或键盘事件来控制页面滚动。以下是两种常见的实现方式:
使用CSS和Vue指令
通过CSS设置全屏容器,结合Vue指令监听滚动事件:
<template>
<div class="fullscreen-container" v-wheel="handleWheel">
<div class="section" v-for="(section, index) in sections" :key="index">
{{ section.content }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
sections: [
{ content: '第一屏内容' },
{ content: '第二屏内容' },
{ content: '第三屏内容' }
],
currentIndex: 0
}
},
directives: {
wheel: {
inserted(el, binding) {
el.addEventListener('wheel', binding.value)
},
unbind(el, binding) {
el.removeEventListener('wheel', binding.value)
}
}
},
methods: {
handleWheel(e) {
e.preventDefault()
if (e.deltaY > 0) {
this.scrollDown()
} else {
this.scrollUp()
}
},
scrollDown() {
if (this.currentIndex < this.sections.length - 1) {
this.currentIndex++
window.scrollTo({
top: window.innerHeight * this.currentIndex,
behavior: 'smooth'
})
}
},
scrollUp() {
if (this.currentIndex > 0) {
this.currentIndex--
window.scrollTo({
top: window.innerHeight * this.currentIndex,
behavior: 'smooth'
})
}
}
}
}
</script>
<style>
.fullscreen-container {
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 ref="fullpage" :options="options"> <div class="section">第一屏</div> <div class="section">第二屏</div> <div class="section">第三屏</div> </full-page> </template>
export default { components: { 'full-page': VueFullPage }, data() { return { options: { licenseKey: 'YOUR_KEY_HERE', scrollingSpeed: 700, navigation: true, anchors: ['page1', 'page2', 'page3'] } } } }
@import 'vue-fullpage.js/dist/vue-fullpage.css'; .section { text-align: center; font-size: 3em; } ```响应式处理
为确保在不同设备上都能正常显示,可以添加响应式处理:
@media (max-width: 768px) {
.section {
font-size: 1.5rem;
}
}
// 在Vue组件中添加触摸事件支持
mounted() {
let startY
this.$el.addEventListener('touchstart', e => {
startY = e.touches[0].clientY
})
this.$el.addEventListener('touchend', e => {
const endY = e.changedTouches[0].clientY
if (startY - endY > 50) {
this.scrollDown()
} else if (endY - startY > 50) {
this.scrollUp()
}
})
}






