vue实现简单轮播组件
组件HTML代码
<div class="banner">
<div
class="swiperList"
v-for="(item, index) in imgUrl"
:key="index"
v-show="currentindex == index"
>
<a href="">
<img :src="item.src" alt="" />
</a>
</div>
<div class="dots">
<span
class="dot"
v-for="(item, index) in imgUrl"
:key="index"
@click="dotClick(index)"
:class="index == currentindex ? 'active' : ''"
></span>
</div>
</div>
</template>
功能代码
<script>
// import banner from "../../assets/img/banner/banner-A.jpg"
export default {
name: "BannerSwiper",
data() {
return {
currentindex: 0,
imgUrl: [
{ src: require("../../assets/img/banner/banner-A.jpg") },
{ src: require("../../assets/img/banner/banner-B.jpg") },
{ src: require("../../assets/img/banner/banner-C.jpg") },
{ src: require("../../assets/img/banner/banner-D.jpg") },
{ src: require("../../assets/img/banner/banner-E.jpg") }
]
};
},
created() {
this.play();
},
methods: {
play() {
//用定时器控制每张图的显示时间
this.timer = setInterval(this.autoPlay, 3000);
},
autoPlay() {
this.currentindex++;
if (this.imgUrl.length == this.currentindex) {
this.currentindex = 0;
}
},
dotClick(index) {
this.currentindex = index;
}
},
beforeUnmount() {
clearInterval(this.timer); //清除定时器
}
};
</script>
样式
<style lang="less" scoped>
.banner {
position: relative;
}
.swiperList {
z-index: 10;
a {
img {
width: 100%;
}
}
}
.dots {
display: flex;
justify-content: center;
margin-top: -20px;
height: 20px;
line-height: 20px;
z-index: 11;
.dot {
width: 10px;
height: 10px;
background: #ffffff;
border-radius: 50%;
margin-left: 10px;
}
.active {
background: #cf0000;
}
}
</style>