vue 实现叠层轮播
实现叠层轮播的思路
叠层轮播(Stacked Carousel)是一种视觉效果,卡片或元素以层叠方式排列,通常仅部分可见,通过滑动或点击切换时产生堆叠动画。Vue 中可通过组合 v-for、CSS 变换和过渡动画实现。
核心代码结构
<template>
<div class="carousel-container">
<div
v-for="(item, index) in items"
:key="item.id"
class="carousel-item"
:style="getItemStyle(index)"
@click="setActive(index)"
>
{{ item.content }}
</div>
</div>
</template>
数据与状态管理
<script>
export default {
data() {
return {
items: [
{ id: 1, content: "Item 1" },
{ id: 2, content: "Item 2" },
{ id: 3, content: "Item 3" }
],
activeIndex: 0
};
},
methods: {
setActive(index) {
this.activeIndex = index;
},
getItemStyle(index) {
const offset = index - this.activeIndex;
const scale = 1 - Math.abs(offset) * 0.1;
const zIndex = this.items.length - Math.abs(offset);
return {
transform: `translateX(${offset * 30}px) scale(${scale})`,
zIndex: zIndex,
opacity: scale
};
}
}
};
</script>
CSS 样式设计
<style scoped>
.carousel-container {
position: relative;
height: 200px;
width: 300px;
margin: 0 auto;
}
.carousel-item {
position: absolute;
width: 80%;
height: 150px;
background: #fff;
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
display: flex;
align-items: center;
justify-content: center;
transition: all 0.3s ease;
cursor: pointer;
}
</style>
动画优化
添加平滑过渡效果可通过调整 transition 属性:

.carousel-item {
transition: transform 0.5s cubic-bezier(0.25, 0.8, 0.25, 1),
opacity 0.3s ease;
}
自动轮播扩展
通过 setInterval 实现自动轮播:

mounted() {
this.interval = setInterval(() => {
this.activeIndex = (this.activeIndex + 1) % this.items.length;
}, 3000);
},
beforeDestroy() {
clearInterval(this.interval);
}
手势支持(可选)
引入 hammer.js 或原生事件实现滑动交互:
methods: {
handleSwipe(direction) {
if (direction === 'left') {
this.activeIndex = Math.min(this.activeIndex + 1, this.items.length - 1);
} else {
this.activeIndex = Math.max(this.activeIndex - 1, 0);
}
}
}
响应式调整
根据屏幕宽度动态计算偏移量:
getItemStyle(index) {
const offset = index - this.activeIndex;
const baseOffset = window.innerWidth < 768 ? 20 : 30;
return {
transform: `translateX(${offset * baseOffset}px)`
};
}






