vue实现翻页滚动
Vue 实现翻页滚动
在 Vue 中实现翻页滚动效果可以通过多种方式完成,以下是一些常见的方法:
使用 CSS Scroll Snap
CSS Scroll Snap 是一种原生支持的滚动翻页效果,无需依赖第三方库。
<template>
<div class="scroll-container">
<div class="scroll-page">Page 1</div>
<div class="scroll-page">Page 2</div>
<div class="scroll-page">Page 3</div>
</div>
</template>
<style>
.scroll-container {
height: 100vh;
overflow-y: scroll;
scroll-snap-type: y mandatory;
}
.scroll-page {
height: 100vh;
scroll-snap-align: start;
}
</style>
使用第三方库(如 vue-scroll-snap)
如果需要更复杂的功能或更好的兼容性,可以使用第三方库。
安装库:
npm install vue-scroll-snap
使用示例:
<template>
<vue-scroll-snap>
<div class="page">Page 1</div>
<div class="page">Page 2</div>
<div class="page">Page 3</div>
</vue-scroll-snap>
</template>
<script>
import VueScrollSnap from "vue-scroll-snap";
export default {
components: {
VueScrollSnap,
},
};
</script>
<style>
.page {
height: 100vh;
}
</style>
自定义滚动逻辑
如果需要完全自定义的翻页滚动效果,可以通过监听滚动事件实现。
<template>
<div class="scroll-container" ref="scrollContainer">
<div class="scroll-page" v-for="page in pages" :key="page">
Page {{ page }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
pages: [1, 2, 3],
currentPage: 0,
};
},
mounted() {
this.$refs.scrollContainer.addEventListener("scroll", this.handleScroll);
},
beforeDestroy() {
this.$refs.scrollContainer.removeEventListener("scroll", this.handleScroll);
},
methods: {
handleScroll() {
const container = this.$refs.scrollContainer;
const pageHeight = container.clientHeight;
const scrollPosition = container.scrollTop;
this.currentPage = Math.round(scrollPosition / pageHeight);
},
},
};
</script>
<style>
.scroll-container {
height: 100vh;
overflow-y: scroll;
}
.scroll-page {
height: 100vh;
}
</style>
使用动画库(如 GSAP)
如果需要更流畅的动画效果,可以结合 GSAP 实现。
安装 GSAP:
npm install gsap
使用示例:

<template>
<div class="scroll-container" ref="scrollContainer">
<div class="scroll-page" v-for="page in pages" :key="page">
Page {{ page }}
</div>
</div>
</template>
<script>
import { gsap } from "gsap";
export default {
data() {
return {
pages: [1, 2, 3],
currentPage: 0,
};
},
methods: {
goToPage(pageIndex) {
const container = this.$refs.scrollContainer;
const pageHeight = container.clientHeight;
gsap.to(container, {
scrollTo: { y: pageIndex * pageHeight, autoKill: false },
duration: 0.5,
});
},
},
};
</script>
<style>
.scroll-container {
height: 100vh;
overflow-y: scroll;
}
.scroll-page {
height: 100vh;
}
</style>
以上方法可以根据需求选择,CSS Scroll Snap 最简单,自定义逻辑最灵活,第三方库和动画库则提供了更多功能和更好的用户体验。






