vue 实现叠层轮播
Vue 实现叠层轮播
叠层轮播(Stacked Carousel)是一种视觉效果,轮播项以层叠方式排列,通常带有缩放或透明度变化。以下是基于 Vue 3 的实现方法。
核心思路
- 使用 CSS 实现叠层布局和动画效果。
- 通过 Vue 的响应式数据控制当前激活项。
- 结合
transform和transition实现平滑切换。
实现步骤
模板部分
<template>
<div class="carousel-container">
<div
v-for="(item, index) in items"
:key="item.id"
class="carousel-item"
:class="{ 'active': currentIndex === index }"
:style="getItemStyle(index)"
>
{{ item.content }}
</div>
<button @click="prev">Prev</button>
<button @click="next">Next</button>
</div>
</template>
脚本部分
<script setup>
import { ref } from 'vue';
const items = [
{ id: 1, content: 'Item 1' },
{ id: 2, content: 'Item 2' },
{ id: 3, content: 'Item 3' },
];
const currentIndex = ref(0);
const next = () => {
currentIndex.value = (currentIndex.value + 1) % items.length;
};
const prev = () => {
currentIndex.value = (currentIndex.value - 1 + items.length) % items.length;
};
const getItemStyle = (index) => {
const offset = index - currentIndex.value;
const scale = 1 - Math.abs(offset) * 0.2;
const zIndex = items.length - Math.abs(offset);
return {
transform: `scale(${scale})`,
zIndex,
opacity: scale,
};
};
</script>
样式部分
<style scoped>
.carousel-container {
position: relative;
width: 300px;
height: 200px;
margin: 0 auto;
}
.carousel-item {
position: absolute;
width: 100%;
height: 100%;
background: #f0f0f0;
border: 1px solid #ccc;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.3s ease;
}
</style>
进阶优化
添加触摸支持
import { useSwipe } from '@vueuse/core';
const container = ref(null);
const { isSwiping, direction } = useSwipe(container);
watch(direction, (dir) => {
if (dir === 'left') next();
if (dir === 'right') prev();
});
自动轮播
import { useIntervalFn } from '@vueuse/core';
useIntervalFn(() => {
next();
}, 3000);
注意事项
- 调整
scale和opacity的计算方式可以改变叠层效果强度。 - 确保容器有明确的宽高和
position: relative。 - 对于复杂场景,可考虑使用现成库如
vue3-carousel的叠层模式。
通过组合 Vue 的响应式特性和 CSS 变换,可以灵活实现各种叠层轮播效果。实际项目中可根据需求调整动画曲线和布局参数。







