vue实现左右切换滑动
Vue 实现左右切换滑动效果
使用 CSS Transition 和 v-if/v-show
通过 Vue 的 v-if 或 v-show 结合 CSS Transition 实现简单的左右滑动效果。定义两个状态,切换时触发动画。
<template>
<div>
<button @click="toggle">切换</button>
<transition name="slide">
<div v-if="show" class="content">内容1</div>
<div v-else class="content">内容2</div>
</transition>
</div>
</template>
<script>
export default {
data() {
return {
show: true
}
},
methods: {
toggle() {
this.show = !this.show;
}
}
}
</script>
<style>
.slide-enter-active, .slide-leave-active {
transition: transform 0.5s ease;
}
.slide-enter {
transform: translateX(100%);
}
.slide-leave-to {
transform: translateX(-100%);
}
.content {
width: 200px;
height: 100px;
background: #eee;
}
</style>
使用第三方库(如 Swiper)
对于更复杂的滑动效果(如轮播、触摸支持),可以直接集成 Swiper.js。

安装 Swiper:
npm install swiper
在 Vue 中使用:

<template>
<swiper
:slides-per-view="1"
:space-between="50"
@swiper="onSwiper"
@slideChange="onSlideChange"
>
<swiper-slide>Slide 1</swiper-slide>
<swiper-slide>Slide 2</swiper-slide>
</swiper>
</template>
<script>
import { Swiper, SwiperSlide } from 'swiper/vue';
import 'swiper/swiper-bundle.css';
export default {
components: {
Swiper,
SwiperSlide
},
methods: {
onSwiper(swiper) {
console.log(swiper);
},
onSlideChange() {
console.log('slide change');
}
}
};
</script>
自定义手势滑动(基于 touch 事件)
通过监听 touchstart、touchmove 和 touchend 事件实现手势滑动。
<template>
<div
class="slider"
@touchstart="handleTouchStart"
@touchmove="handleTouchMove"
@touchend="handleTouchEnd"
>
<div class="slide" :style="slideStyle">滑动内容</div>
</div>
</template>
<script>
export default {
data() {
return {
startX: 0,
currentX: 0,
isDragging: false
}
},
computed: {
slideStyle() {
return {
transform: `translateX(${this.currentX}px)`
};
}
},
methods: {
handleTouchStart(e) {
this.startX = e.touches[0].clientX;
this.isDragging = true;
},
handleTouchMove(e) {
if (!this.isDragging) return;
this.currentX = e.touches[0].clientX - this.startX;
},
handleTouchEnd() {
this.isDragging = false;
// 判断滑动方向
if (this.currentX > 50) {
// 向右滑动逻辑
} else if (this.currentX < -50) {
// 向左滑动逻辑
}
this.currentX = 0;
}
}
}
</script>
使用 Vue 动画钩子
通过 Vue 的 JavaScript 动画钩子实现更精细的控制。
<template>
<div>
<button @click="toggle">切换</button>
<transition
@before-enter="beforeEnter"
@enter="enter"
@leave="leave"
>
<div v-if="show" class="box"></div>
</transition>
</div>
</template>
<script>
export default {
data() {
return {
show: true
}
},
methods: {
toggle() {
this.show = !this.show;
},
beforeEnter(el) {
el.style.transform = 'translateX(100%)';
},
enter(el, done) {
const animation = el.animate(
[{ transform: 'translateX(100%)' }, { transform: 'translateX(0)' }],
{ duration: 500 }
);
animation.onfinish = () => {
done();
};
},
leave(el, done) {
const animation = el.animate(
[{ transform: 'translateX(0)' }, { transform: 'translateX(-100%)' }],
{ duration: 500 }
);
animation.onfinish = () => {
done();
};
}
}
}
</script>






