vuecli用组件写一个简易轮播图并且点击下方标题可展示相应的图片的
时间: 2023-06-15 22:07:19 浏览: 112
好的,以下是一个简易的轮播图组件示例:
```vue
<template>
<div class="carousel">
<div class="carousel-images">
<img v-for="(image, index) in images" :key="index" :src="image" :class="{ active: index === activeIndex }">
</div>
<div class="carousel-titles">
<div v-for="(title, index) in titles" :key="index" :class="{ active: index === activeIndex }" @click="setActive(index)">{{ title }}</div>
</div>
</div>
</template>
<script>
export default {
name: 'Carousel',
props: {
images: {
type: Array,
required: true
},
titles: {
type: Array,
required: true
}
},
data() {
return {
activeIndex: 0
}
},
methods: {
setActive(index) {
this.activeIndex = index
}
}
}
</script>
<style>
.carousel {
position: relative;
width: 100%;
height: 400px;
}
.carousel-images {
position: absolute;
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
.carousel-images img {
position: absolute;
width: 100%;
height: 100%;
object-fit: cover;
opacity: 0;
transition: opacity 0.5s ease-in-out;
}
.carousel-images img.active {
opacity: 1;
}
.carousel-titles {
position: absolute;
bottom: 0;
left: 0;
width: 100%;
display: flex;
justify-content: center;
background-color: rgba(0, 0, 0, 0.7);
}
.carousel-titles div {
padding: 10px;
color: #fff;
cursor: pointer;
transition: background-color 0.5s ease-in-out;
}
.carousel-titles div.active {
background-color: rgba(255, 255, 255, 0.3);
}
</style>
```
在父组件中可以通过传入 `images` 和 `titles` 数组来使用该组件:
```vue
<template>
<div>
<carousel :images="images" :titles="titles" />
</div>
</template>
<script>
import Carousel from '@/components/Carousel'
export default {
name: 'App',
components: {
Carousel
},
data() {
return {
images: [
'https://picsum.photos/800/400?random=1',
'https://picsum.photos/800/400?random=2',
'https://picsum.photos/800/400?random=3'
],
titles: [
'Image 1',
'Image 2',
'Image 3'
]
}
}
}
</script>
```
注意:该示例只包含了基本的轮播功能,若需要更加复杂的轮播效果,可以考虑使用第三方的轮播插件。
阅读全文