vue实现页面滑动切换
Vue实现页面滑动切换的方法
使用vue-router和CSS过渡动画
在Vue项目中配置vue-router,结合CSS过渡效果实现滑动切换。在App.vue或布局组件中添加过渡效果:
<template>
<router-view v-slot="{ Component }">
<transition name="slide">
<component :is="Component" />
</transition>
</router-view>
</template>
<style>
.slide-enter-active,
.slide-leave-active {
transition: transform 0.5s ease;
}
.slide-enter-from {
transform: translateX(100%);
}
.slide-leave-to {
transform: translateX(-100%);
}
</style>
使用第三方库vue-page-transition
安装vue-page-transition库可以快速实现多种页面过渡效果:
npm install vue-page-transition
在main.js中注册插件:

import VuePageTransition from 'vue-page-transition'
Vue.use(VuePageTransition)
在组件中使用:
<vue-page-transition name="fade-in-right">
<router-view/>
</vue-page-transition>
手势滑动检测实现
结合Hammer.js等手势库检测滑动事件:

import Hammer from 'hammerjs'
export default {
mounted() {
const hammer = new Hammer(this.$el)
hammer.on('swipeleft', () => {
this.$router.push('/next-page')
})
hammer.on('swiperight', () => {
this.$router.go(-1)
})
}
}
全屏滑动组件方案
创建可滑动的全屏组件容器:
<template>
<div class="swiper-container" @touchstart="touchStart" @touchmove="touchMove">
<div class="slide" v-for="(slide, index) in slides" :key="index">
{{ slide.content }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
startX: 0,
slides: [
{ content: '页面1' },
{ content: '页面2' }
]
}
},
methods: {
touchStart(e) {
this.startX = e.touches[0].clientX
},
touchMove(e) {
const moveX = e.touches[0].clientX - this.startX
if (moveX > 50) {
// 向右滑动处理
} else if (moveX < -50) {
// 向左滑动处理
}
}
}
}
</script>
<style>
.swiper-container {
width: 100vw;
height: 100vh;
overflow: hidden;
position: relative;
}
.slide {
width: 100%;
height: 100%;
position: absolute;
}
</style>
响应式滑动阈值控制
根据屏幕宽度动态调整滑动阈值:
methods: {
touchMove(e) {
const moveX = e.touches[0].clientX - this.startX
const threshold = window.innerWidth * 0.2
if (Math.abs(moveX) > threshold) {
this.handleSwipe(moveX > 0 ? 'right' : 'left')
}
},
handleSwipe(direction) {
if (direction === 'left') {
this.$router.push(this.nextRoute)
} else {
this.$router.go(-1)
}
}
}
这些方法可以根据项目需求单独或组合使用,实现不同复杂度的页面滑动切换效果。CSS过渡方案适合简单场景,手势库方案提供更精细的控制,而全屏组件适合需要完全自定义滑动行为的情况。






