vue实现卡片叠加滑动
Vue实现卡片叠加滑动效果
实现卡片叠加滑动效果可以通过CSS和Vue的动画过渡功能结合完成。以下是具体实现方法:
基础HTML结构
<template>
<div class="card-stack">
<div
v-for="(card, index) in cards"
:key="card.id"
:style="{ zIndex: cards.length - index }"
class="card"
@click="handleSwipe(index)"
>
{{ card.content }}
</div>
</div>
</template>
Vue数据与交互逻辑
<script>
export default {
data() {
return {
cards: [
{ id: 1, content: 'Card 1' },
{ id: 2, content: 'Card 2' },
{ id: 3, content: 'Card 3' }
]
}
},
methods: {
handleSwipe(index) {
// 移除最顶层卡片
this.cards.splice(index, 1);
// 可选:添加新卡片到底部
// this.cards.push({
// id: Date.now(),
// content: `Card ${this.cards.length + 1}`
// });
}
}
}
</script>
CSS样式与动画

<style scoped>
.card-stack {
position: relative;
width: 300px;
height: 400px;
margin: 0 auto;
}
.card {
position: absolute;
width: 100%;
height: 100%;
background: white;
border-radius: 10px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
display: flex;
align-items: center;
justify-content: center;
font-size: 24px;
transition: all 0.3s ease;
cursor: pointer;
}
/* 卡片堆叠效果 */
.card:nth-child(1) { transform: translateY(0) scale(1); }
.card:nth-child(2) { transform: translateY(10px) scale(0.95); }
.card:nth-child(3) { transform: translateY(20px) scale(0.9); }
/* 滑动动画 */
.card.swipe-left {
transform: translateX(-200%) rotate(-30deg) !important;
opacity: 0;
}
.card.swipe-right {
transform: translateX(200%) rotate(30deg) !important;
opacity: 0;
}
</style>
进阶实现:拖拽滑动
对于需要拖拽滑动的实现,可以结合@touchstart、@touchmove和@touchend事件(或对应的鼠标事件):
拖拽逻辑
methods: {
startDrag(e, index) {
this.dragging = {
index,
startX: e.touches ? e.touches[0].clientX : e.clientX,
startY: e.touches ? e.touches[0].clientY : e.clientY
};
},
duringDrag(e) {
if (!this.dragging) return;
const currentX = e.touches ? e.touches[0].clientX : e.clientX;
const offsetX = currentX - this.dragging.startX;
const card = this.$refs.cards[this.dragging.index];
card.style.transform = `translateX(${offsetX}px) rotate(${offsetX * 0.1}deg)`;
},
endDrag(e) {
if (!this.dragging) return;
const currentX = e.changedTouches ? e.changedTouches[0].clientX : e.clientX;
const offsetX = currentX - this.dragging.startX;
if (Math.abs(offsetX) > 100) {
// 滑动超过阈值,移除卡片
this.cards.splice(this.dragging.index, 1);
} else {
// 回弹动画
this.$refs.cards[this.dragging.index].style.transform = '';
}
this.dragging = null;
}
}
对应HTML修改

<div
v-for="(card, index) in cards"
:key="card.id"
:ref="'cards'"
@touchstart="startDrag($event, index)"
@mousedown="startDrag($event, index)"
@touchmove="duringDrag"
@mousemove="duringDrag"
@touchend="endDrag"
@mouseup="endDrag"
@mouseleave="endDrag"
>
使用第三方库
对于更复杂的效果,可以考虑使用专门库:
vue-swipe-cards: 专门为Vue设计的卡片滑动组件hammer.js: 手势识别库,可处理复杂手势vue-draggable: 实现拖拽排序功能
安装示例:
npm install vue-swipe-cards
使用示例:
import VueSwipeCards from 'vue-swipe-cards';
export default {
components: {
'swipe-cards': VueSwipeCards
},
// ...其他配置
}
以上方案可根据具体需求选择基础实现或进阶实现,第三方库能快速实现专业级效果但会增加项目体积。






