vue组件实现完整轮播图
时间: 2023-06-11 14:08:52 浏览: 81
好的,以下是一个基于 Vue 的完整轮播图组件:
```html
<template>
<div class="carousel-wrapper">
<div class="carousel-container" :style="{ transform: `translateX(${translateX}px)` }">
<div v-for="(item, index) in items" :key="index" class="carousel-item">
<img :src="item.imgUrl" alt="">
<div class="carousel-item-title">{{ item.title }}</div>
</div>
</div>
<div class="carousel-indicators">
<span v-for="(item, index) in items" :key="index" :class="{ active: index === currentIndex }" @click="handleIndicatorClick(index)"></span>
</div>
</div>
</template>
<script>
export default {
data() {
return {
currentIndex: 0,
translateX: 0,
items: [
{
imgUrl: 'https://picsum.photos/id/237/200/300',
title: 'Slide 1'
},
{
imgUrl: 'https://picsum.photos/id/238/200/300',
title: 'Slide 2'
},
{
imgUrl: 'https://picsum.photos/id/239/200/300',
title: 'Slide 3'
},
{
imgUrl: 'https://picsum.photos/id/240/200/300',
title: 'Slide 4'
}
]
}
},
methods: {
handleIndicatorClick(index) {
this.currentIndex = index
this.translateX = -index * 100
},
handlePrev() {
if (this.currentIndex > 0) {
this.currentIndex--
this.translateX += 100
}
},
handleNext() {
if (this.currentIndex < this.items.length - 1) {
this.currentIndex++
this.translateX -= 100
}
}
}
}
</script>
<style>
.carousel-wrapper {
position: relative;
width: 100%;
height: 300px;
overflow: hidden;
}
.carousel-container {
display: flex;
transition: transform 0.3s ease;
}
.carousel-item {
position: relative;
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
.carousel-item img {
width: 100%;
height: 100%;
object-fit: cover;
}
.carousel-item-title {
position: absolute;
bottom: 0;
left: 0;
width: 100%;
padding: 10px;
text-align: center;
background-color: rgba(0, 0, 0, 0.5);
color: #fff;
}
.carousel-indicators {
position: absolute;
bottom: 10px;
left: 50%;
transform: translateX(-50%);
display: flex;
}
.carousel-indicators span {
display: inline-block;
width: 10px;
height: 10px;
border-radius: 50%;
background-color: #fff;
margin-right: 10px;
cursor: pointer;
}
.carousel-indicators span.active {
background-color: red;
}
</style>
```
这个组件包含以下功能:
- 自动轮播
- 手动点击指示器切换轮播图
- 左右箭头切换轮播图
如果还需要其他功能,可以在这个基础上进行扩展。
阅读全文