vue实现滑动卡片切换
Vue 实现滑动卡片切换
使用 Vue 和 CSS 实现基础滑动效果
通过 Vue 的 v-for 和 CSS 过渡效果实现卡片滑动切换。定义一个数组存储卡片数据,使用 v-for 渲染卡片列表。
<template>
<div class="card-container">
<div
v-for="(card, index) in cards"
:key="index"
class="card"
:style="{ transform: `translateX(${currentIndex * -100}%)` }"
>
{{ card.content }}
</div>
</div>
<button @click="prev">上一张</button>
<button @click="next">下一张</button>
</template>
<script>
export default {
data() {
return {
cards: [
{ content: '卡片1' },
{ content: '卡片2' },
{ content: '卡片3' }
],
currentIndex: 0
};
},
methods: {
prev() {
this.currentIndex = Math.max(0, this.currentIndex - 1);
},
next() {
this.currentIndex = Math.min(this.cards.length - 1, this.currentIndex + 1);
}
}
};
</script>
<style>
.card-container {
display: flex;
overflow: hidden;
width: 300px;
}
.card {
flex: 0 0 100%;
transition: transform 0.3s ease;
padding: 20px;
background: #eee;
margin: 10px 0;
}
</style>
添加触摸事件支持
为移动端添加触摸事件支持,通过 touchstart、touchmove 和 touchend 实现滑动切换。
<template>
<div
class="card-container"
@touchstart="handleTouchStart"
@touchmove="handleTouchMove"
@touchend="handleTouchEnd"
>
<!-- 卡片内容同上 -->
</div>
</template>
<script>
export default {
data() {
return {
touchStartX: 0,
touchEndX: 0
};
},
methods: {
handleTouchStart(e) {
this.touchStartX = e.touches[0].clientX;
},
handleTouchMove(e) {
this.touchEndX = e.touches[0].clientX;
},
handleTouchEnd() {
if (this.touchEndX < this.touchStartX - 50) {
this.next();
} else if (this.touchEndX > this.touchStartX + 50) {
this.prev();
}
}
}
};
</script>
使用第三方库实现高级效果
引入 swiper 或 vue-awesome-swiper 库实现更丰富的滑动效果。
安装 swiper:
npm install swiper vue-awesome-swiper
使用示例:
<template>
<swiper :options="swiperOptions">
<swiper-slide v-for="(card, index) in cards" :key="index">
{{ card.content }}
</swiper-slide>
</swiper>
</template>
<script>
import { Swiper, SwiperSlide } from 'vue-awesome-swiper';
import 'swiper/css/swiper.css';
export default {
components: {
Swiper,
SwiperSlide
},
data() {
return {
cards: [
{ content: '卡片1' },
{ content: '卡片2' },
{ content: '卡片3' }
],
swiperOptions: {
slidesPerView: 1,
spaceBetween: 10,
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev'
}
}
};
}
};
</script>
动画优化与性能调整
通过 CSS will-change 属性优化动画性能,避免不必要的重绘。
.card {
will-change: transform;
}
响应式设计适配
根据屏幕宽度动态调整卡片显示数量,通过计算属性或媒体查询实现。
computed: {
swiperOptions() {
return {
slidesPerView: window.innerWidth < 768 ? 1 : 2,
spaceBetween: 10
};
}
}






