vue实现卡片切换
Vue 实现卡片切换的方法
使用 v-if/v-else 或 v-show 控制显示
通过 Vue 的指令可以轻松切换卡片显示状态。v-if 会销毁和重建 DOM 元素,适合切换频率低的场景;v-show 只是切换 CSS 的 display 属性,适合频繁切换的场景。
<template>
<div>
<button @click="showCard1 = !showCard1">切换卡片</button>
<div v-if="showCard1" class="card">卡片1内容</div>
<div v-else class="card">卡片2内容</div>
</div>
</template>
<script>
export default {
data() {
return {
showCard1: true
}
}
}
</script>
使用动态组件
Vue 的 <component> 元素配合 is 属性可以实现动态组件切换,适合更复杂的卡片切换场景。
<template>
<div>
<button @click="currentComponent = 'Card1'">显示卡片1</button>
<button @click="currentComponent = 'Card2'">显示卡片2</button>
<component :is="currentComponent"></component>
</div>
</template>
<script>
import Card1 from './Card1.vue'
import Card2 from './Card2.vue'
export default {
components: {
Card1,
Card2
},
data() {
return {
currentComponent: 'Card1'
}
}
}
</script>
使用 Vue Transition 添加动画效果
为卡片切换添加过渡动画可以提升用户体验,Vue 提供了 <transition> 组件来实现。

<template>
<div>
<button @click="show = !show">切换卡片</button>
<transition name="fade">
<div v-if="show" class="card">卡片内容</div>
</transition>
</div>
</template>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity .5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>
使用第三方库实现更复杂效果
对于需要轮播、3D 翻转等复杂效果的卡片切换,可以考虑使用第三方库如 Swiper.js 或 vue-awesome-swiper。
安装 vue-awesome-swiper:

npm install swiper vue-awesome-swiper
使用示例:
<template>
<swiper>
<swiper-slide>卡片1</swiper-slide>
<swiper-slide>卡片2</swiper-slide>
<swiper-slide>卡片3</swiper-slide>
</swiper>
</template>
<script>
import { Swiper, SwiperSlide } from 'vue-awesome-swiper'
import 'swiper/css/swiper.css'
export default {
components: {
Swiper,
SwiperSlide
}
}
</script>
通过数组循环和索引控制
当卡片数量较多时,可以通过数组和索引来控制当前显示的卡片。
<template>
<div>
<button @click="prevCard">上一张</button>
<button @click="nextCard">下一张</button>
<div class="card">{{ cards[currentIndex] }}</div>
</div>
</template>
<script>
export default {
data() {
return {
cards: ['卡片1内容', '卡片2内容', '卡片3内容'],
currentIndex: 0
}
},
methods: {
nextCard() {
this.currentIndex = (this.currentIndex + 1) % this.cards.length
},
prevCard() {
this.currentIndex = (this.currentIndex - 1 + this.cards.length) % this.cards.length
}
}
}
</script>
每种方法适用于不同的场景,可以根据项目需求选择最合适的实现方式。简单的显示隐藏使用 v-if/v-show,需要动画效果添加 transition,复杂轮播效果推荐使用第三方库。






