vue实现卡片叠加滑动
Vue 实现卡片叠加滑动效果
实现卡片叠加滑动效果可以通过 CSS 结合 Vue 的动态数据绑定和过渡动画完成。以下是具体实现方法:
依赖准备
确保项目中已安装 Vue 及相关动画库(如 vue-transition 或直接使用原生 CSS 过渡)。
基本数据结构
在 Vue 的 data 中定义卡片数组和当前激活的卡片索引:
data() {
return {
cards: [
{ id: 1, title: 'Card 1' },
{ id: 2, title: 'Card 2' },
{ id: 3, title: 'Card 3' }
],
activeIndex: 0
}
}
模板结构
使用 v-for 渲染卡片,并通过 z-index 和 transform 控制叠加效果:
<div class="card-container">
<div
v-for="(card, index) in cards"
:key="card.id"
class="card"
:style="{
zIndex: cards.length - index,
transform: getCardTransform(index)
}"
@click="activateCard(index)"
>
{{ card.title }}
</div>
</div>
样式设计 通过 CSS 实现叠加和滑动动画:
.card-container {
position: relative;
width: 300px;
height: 200px;
margin: 0 auto;
}
.card {
position: absolute;
width: 100%;
height: 100%;
background: #fff;
border-radius: 8px;
box-shadow: 0 4px 12px rgba(0,0,0,0.1);
transition: transform 0.3s ease;
cursor: pointer;
}
动态位置计算 在 Vue 方法中计算每张卡片的偏移量:
methods: {
getCardTransform(index) {
const offset = 20; // 叠加偏移量
const activeOffset = index === this.activeIndex ? 0 : 10;
return `translate(${index * offset}px, ${index * offset - activeOffset}px)`;
},
activateCard(index) {
this.activeIndex = index;
}
}
进阶交互
添加滑动动画和手势控制(需引入 hammerjs 等库):
import Hammer from 'hammerjs';
mounted() {
const container = document.querySelector('.card-container');
const hammer = new Hammer(container);
hammer.on('swipeleft', () => {
this.activeIndex = Math.min(this.activeIndex + 1, this.cards.length - 1);
});
hammer.on('swiperight', () => {
this.activeIndex = Math.max(this.activeIndex - 1, 0);
});
}
响应式调整
通过 Vue 的 computed 属性实现响应式布局:
computed: {
visibleCards() {
return this.cards.slice(
Math.max(0, this.activeIndex - 2),
this.activeIndex + 1
).reverse();
}
}
最终效果
- 卡片会以堆叠形式展示,最上层卡片完全可见
- 点击或滑动时切换激活卡片
- 非激活卡片自动下沉并偏移形成立体效果
通过调整 CSS 的 transform 属性和过渡时间,可以进一步优化动画流畅度。对于移动端,建议增加触摸事件处理以提高交互体验。







