vue实现切换左右功能
Vue实现左右切换功能
使用CSS过渡和v-if/v-show
通过Vue的v-if或v-show指令结合CSS过渡效果实现左右切换动画效果。定义一个状态变量控制当前显示内容。
<template>
<div class="slider-container">
<button @click="toggle">切换</button>
<transition name="slide">
<div v-if="showLeft" class="content left">左侧内容</div>
<div v-else class="content right">右侧内容</div>
</transition>
</div>
</template>
<script>
export default {
data() {
return {
showLeft: true
}
},
methods: {
toggle() {
this.showLeft = !this.showLeft
}
}
}
</script>
<style>
.slide-enter-active, .slide-leave-active {
transition: transform 0.5s ease;
}
.slide-enter-from {
transform: translateX(100%);
}
.slide-leave-to {
transform: translateX(-100%);
}
.content {
position: absolute;
width: 100%;
}
</style>
使用动态组件
通过Vue的动态组件<component :is="">实现左右内容切换,适合更复杂的组件切换场景。

<template>
<div>
<button @click="currentComponent = 'LeftComponent'">显示左侧</button>
<button @click="currentComponent = 'RightComponent'">显示右侧</button>
<transition name="fade">
<component :is="currentComponent" />
</transition>
</div>
</template>
<script>
import LeftComponent from './LeftComponent.vue'
import RightComponent from './RightComponent.vue'
export default {
components: {
LeftComponent,
RightComponent
},
data() {
return {
currentComponent: 'LeftComponent'
}
}
}
</script>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter-from, .fade-leave-to {
opacity: 0;
}
</style>
使用第三方库
对于更复杂的滑动效果,可以使用第三方库如vue-slick或swiper-vue实现轮播效果。
安装vue-slick:

npm install vue-slick-carousel
实现代码:
<template>
<vue-slick-carousel :arrows="true" :dots="true">
<div class="slide">左侧内容</div>
<div class="slide">右侧内容</div>
</vue-slick-carousel>
</template>
<script>
import VueSlickCarousel from 'vue-slick-carousel'
export default {
components: { VueSlickCarousel }
}
</script>
手势滑动支持
添加触摸事件支持实现手势滑动切换,增强移动端用户体验。
<template>
<div
class="swipe-container"
@touchstart="touchStart"
@touchmove="touchMove"
@touchend="touchEnd"
>
<div class="content" :style="contentStyle">
<div class="left">左侧内容</div>
<div class="right">右侧内容</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
startX: 0,
moveX: 0,
currentIndex: 0
}
},
computed: {
contentStyle() {
return {
transform: `translateX(${-this.currentIndex * 100 + this.moveX}px)`,
transition: this.moveX ? 'none' : 'transform 0.3s ease'
}
}
},
methods: {
touchStart(e) {
this.startX = e.touches[0].clientX
},
touchMove(e) {
this.moveX = e.touches[0].clientX - this.startX
},
touchEnd() {
if (Math.abs(this.moveX) > 50) {
if (this.moveX > 0 && this.currentIndex > 0) {
this.currentIndex--
} else if (this.moveX < 0 && this.currentIndex < 1) {
this.currentIndex++
}
}
this.moveX = 0
}
}
}
</script>
<style>
.swipe-container {
overflow: hidden;
position: relative;
width: 100%;
height: 200px;
}
.content {
display: flex;
width: 200%;
height: 100%;
}
.left, .right {
width: 50%;
}
</style>






