vue3实现淡出淡入轮播图完整实例
时间: 2023-07-12 14:51:04 浏览: 190
好的,以下是一个使用 Vue3 实现淡出淡入轮播图的完整实例:
```vue
<template>
<div class="carousel-container">
<div class="carousel-slide">
<transition-group name="fade" mode="out-in">
<div :key="currentSlide" class="carousel-slide-item">
<img :src="slides[currentSlide]" class="carousel-slide-img">
</div>
</transition-group>
</div>
<div class="carousel-dots">
<span v-for="(slide, index) in slides" :key="index" class="carousel-dot" :class="{ active: currentSlide === index }" @click="jumpToSlide(index)"></span>
</div>
</div>
</template>
<script>
import { ref } from 'vue';
export default {
name: 'Carousel',
props: {
slides: {
type: Array,
required: true
}
},
setup(props) {
const currentSlide = ref(0);
const jumpToSlide = index => {
currentSlide.value = index;
};
const nextSlide = () => {
currentSlide.value = (currentSlide.value + 1) % props.slides.length;
};
setInterval(nextSlide, 5000);
return {
currentSlide,
jumpToSlide
};
}
};
</script>
<style>
.carousel-container {
position: relative;
overflow: hidden;
}
.carousel-slide {
position: relative;
height: 500px;
}
.carousel-slide-item {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.carousel-slide-img {
width: 100%;
height: 100%;
object-fit: cover;
}
.carousel-dots {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
display: flex;
justify-content: center;
}
.carousel-dot {
width: 10px;
height: 10px;
margin: 0 10px;
border-radius: 50%;
background-color: #fff;
cursor: pointer;
transition: transform 0.3s ease;
}
.carousel-dot.active {
transform: scale(1.5);
}
.fade-enter-active,
.fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter,
.fade-leave-to {
opacity: 0;
}
</style>
```
该组件使用了 `ref` 来创建响应式数据 `currentSlide`,并且在 `setup` 函数中使用了计时器来每隔5秒钟自动切换轮播图。该组件还包括了一个 `jumpToSlide` 方法,用于实现点击小圆点跳转到指定的轮播图。在模板中,使用了 Vue3 的 `<transition-group>` 组件来实现淡入淡出效果。同时,还使用了 CSS3 的 `transform` 和 `transition` 属性来实现小圆点的缩放效果。
阅读全文