使用vue3写轮播图带注释
时间: 2023-05-27 12:04:13 浏览: 95
<template>
<div class="carousel">
<div class="item"
v-for="(img, index) in images"
:key="index"
:class="{'active': index === currentIndex}">
<img :src="img.src" :alt="img.alt" />
<div class="caption">{{ img.caption }}</div>
</div>
</div>
</template>
<script>
import { ref, watchEffect } from 'vue';
export default {
name: 'Carousel',
props: {
images: {
type: Array,
required: true,
},
autoplay: {
type: Boolean,
default: true,
},
interval: {
type: Number,
default: 5000,
},
},
setup(props) {
const currentIndex = ref(0);
const timer = ref(null);
// 监听当前索引变化
watchEffect(() => {
if (currentIndex.value >= props.images.length) {
currentIndex.value = 0;
} else if (currentIndex.value < 0) {
currentIndex.value = props.images.length - 1;
}
});
// 循环播放功能
const loopSlides = () => {
timer.value = setInterval(() => {
currentIndex.value++;
}, props.interval);
};
// 停止自动播放功能
const stopLoop = () => {
clearInterval(timer.value);
timer.value = null;
};
// 监听autoplay属性变化
watchEffect(() => {
if (props.autoplay) {
loopSlides();
} else {
stopLoop();
}
});
return {
currentIndex,
};
},
};
</script>
<style scoped>
.carousel {
position: relative;
width: 100%;
height: 100%;
overflow: hidden;
}
.item {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0;
z-index: 1;
transition: opacity 0.5s ease;
}
.item.active {
opacity: 1;
z-index: 2;
}
.caption {
position: absolute;
bottom: 0;
left: 0;
width: 100%;
padding: 10px;
box-sizing: border-box;
font-size: 14px;
color: #fff;
background-color: rgba(0, 0, 0, 0.6);
text-align: center;
}
</style>
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![.zip](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)