请用vue封装一个轮播图组件
时间: 2023-07-13 16:32:08 浏览: 94
基于vue的轮播图
好的,以下是一个基于Vue.js实现的轮播图组件:
```html
<template>
<div class="slider">
<div class="slider-wrapper"
:style="{ transform: 'translateX(-' + currentImage * 100 + '%)' }">
<div class="slider-item"
v-for="(image, index) in images"
:key="index"
:style="{ backgroundImage: 'url(' + image + ')' }">
</div>
</div>
<div class="slider-dots">
<span class="dot"
v-for="(image, index) in images"
:key="index"
:class="{ active: currentImage === index }"
@click="goToImage(index)">
</span>
</div>
</div>
</template>
<script>
export default {
data() {
return {
currentImage: 0,
interval: null,
};
},
props: {
images: {
type: Array,
required: true,
},
intervalTime: {
type: Number,
default: 3000,
},
},
methods: {
startSlider() {
this.interval = setInterval(() => {
this.currentImage++;
if (this.currentImage >= this.images.length) {
this.currentImage = 0;
}
}, this.intervalTime);
},
goToImage(index) {
this.currentImage = index;
clearInterval(this.interval);
this.startSlider();
},
},
mounted() {
this.startSlider();
},
beforeUnmount() {
clearInterval(this.interval);
},
};
</script>
<style scoped>
.slider {
position: relative;
overflow: hidden;
}
.slider-wrapper {
display: flex;
transition: transform 0.5s ease-out;
}
.slider-item {
width: 100%;
height: 0;
padding-bottom: 56.25%;
background-position: center;
background-size: cover;
}
.slider-dots {
position: absolute;
bottom: 10px;
left: 50%;
transform: translateX(-50%);
display: flex;
}
.slider-dots .dot {
width: 10px;
height: 10px;
border-radius: 50%;
background-color: #ccc;
margin-right: 10px;
cursor: pointer;
}
.slider-dots .active {
background-color: #333;
}
</style>
```
这个轮播图组件接受一个`images`数组作为参数,每个元素是一个图片的URL。可以通过设置`intervalTime`属性来控制自动播放的时间间隔,默认为3秒。组件内部使用了`setInterval`函数来实现自动播放,并且在组件销毁前使用`clearInterval`函数清除定时器。底部的小圆点会根据当前显示的图片来更新样式,并且可以点击切换到对应的图片。
阅读全文