使用vue3写轮播图带注释
时间: 2023-07-08 16:16:47 浏览: 130
基于vue.js实现图片轮播效果
好的,以下是一个使用Vue3写的轮播图组件,同时带有图片注释的示例代码:
```html
<template>
<div class="carousel-container">
<div class="carousel">
<img v-for="(image, index) in images"
:key="index"
:src="image.src"
:alt="image.title"
:class="{ active: index === currentSlide }"
@click="showCaption(index)">
<div class="caption"
:class="{ active: showCaptionBox }">
<p>{{ images[currentSlide].title }}</p>
</div>
</div>
<div class="carousel-nav">
<button @click="prevSlide"><</button>
<button @click="nextSlide">></button>
</div>
</div>
</template>
<script>
import { defineComponent, ref } from 'vue';
export default defineComponent({
name: 'Carousel',
props: {
images: {
type: Array,
required: true,
default: () => [],
},
},
setup(props) {
const currentSlide = ref(0);
const showCaptionBox = ref(false);
const prevSlide = () => {
currentSlide.value = (currentSlide.value + props.images.length - 1) % props.images.length;
};
const nextSlide = () => {
currentSlide.value = (currentSlide.value + 1) % props.images.length;
};
const showCaption = (index) => {
currentSlide.value = index;
showCaptionBox.value = true;
};
return {
currentSlide,
showCaptionBox,
prevSlide,
nextSlide,
showCaption,
};
},
});
</script>
<style>
.carousel-container {
position: relative;
width: 100%;
height: 400px;
}
.carousel {
position: relative;
width: 100%;
height: 100%;
overflow: hidden;
}
.carousel img {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0;
transition: opacity 0.5s ease-in-out;
}
.carousel img.active {
opacity: 1;
}
.carousel .caption {
position: absolute;
bottom: 0;
left: 0;
width: 100%;
background: rgba(0, 0, 0, 0.5);
color: #fff;
font-size: 16px;
text-align: center;
padding: 20px;
opacity: 0;
transform: translateY(100%);
transition: all 0.5s ease-in-out;
}
.carousel .caption.active {
opacity: 1;
transform: translateY(0%);
}
.carousel-nav {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
display: flex;
}
.carousel-nav button {
background: #fff;
border: none;
padding: 10px;
font-size: 20px;
margin: 0 10px;
cursor: pointer;
}
</style>
```
此组件支持传入图片数组,每张图片包含 `src` 和 `title` 两个属性。当用户点击某张图片时,会显示该图片的标题注释。用户可以通过轮播图上的左右箭头切换图片,轮播图支持循环播放。
阅读全文