<template>
<div class="banner">
<div class="box" @mouseout="stop" @mouseover="start">
<!-- 轮播图片 -->
<img v-for="(item, index) in bannerList" v-show="listIndex === index" :key="index"
:src="item" alt="">
<!-- 左切换图片箭头 -->
<span class="left" @click="clickIcon(index)"><</span>
<!-- 右切换图片箭头 -->
<span class="right" @click="clickIcon(index)">></span>
<!-- 圆点切换按钮 -->
<ul>
<li v-for="(item, index) in bannerList" @click="changePage(index)" :key="index"
:class="{ color: index == listIndex }">
</li>
</ul>
</div>
</div>
</template>
<script>
export default {
data() {
return {
listIndex: 0, //默认显示第几张图片
timer: null, //定时器
bannerList: [
require("@/assets/images/banner01.png"),
require("@/assets/images/banner02.png"),
require("@/assets/images/banner03.png"),
require("@/assets/images/banner04.png"),
]
}
},
methods: {
//开启定时器
startInterval() {
// 事件里定时器应该先清除在设置,防止多次点击直接生成多个定时器
clearInterval(this.timer);
this.timer = setInterval(() => {
this.listIndex++;
if (this.listIndex > this.bannerList.length - 1) {
this.listIndex = 0
}
}, 1000);
},
// 鼠标移除开启定时器
stop() {
this.startInterval();
},
// 鼠标移入清除定时器
start() {
clearInterval(this.timer);
},
// // 点击控制圆点
changePage(index) {
this.listIndex = index;
},
// 箭头切换图片
clickIcon(val) {
if (val === 'index') {
this.listIndex++;
if (this.listIndex === this.bannerList.length) {
this.listIndex = 0;
}
} else {
/* 第一种写法
this.listIndex--;
if(this.listIndex < 0){
this.listIndex = this.bannerList.length-1;
} */
// 第二种写法
if (this.listIndex === 0) {
this.listIndex = this.bannerList.length;
}
this.listIndex--;
}
},
},
//进入页面后启动定时轮播 //生命周期
mounted() {
this.startInterval()
},
}
</script>
<style lang="scss" scoped>
.banner {
display: flex;
width: 1000px;
height: 440px;
align-items: center;
justify-content: center;
background-color: #62f69b;
margin: 0 auto;
.box {
display: flex;
position: relative;
width: 1000px;
height: 440px;
img {
width: 100%;
height: 100%;
}
span {
display: flex;
color: white;
font-size: 28px;
width: 40px;
height: 40px;
border-radius: 100px;
justify-content: center;
align-items: center;
background-color: rgb(0, 0, 0, 0.5);
}
.left {
position: absolute;
left: 8px;
top: 46%;
}
.right {
position: absolute;
right: 8px;
top: 46%;
}
ul {
display: flex;
justify-content: center;
position: absolute;
width: 1000px;
bottom: 22px;
.color {
background: red;
color: red;
}
li {
width: 10px;
height: 10px;
margin-left: 20px;
background: white;
border-radius: 50%;
}
}
}
}
</style>
刚开始学Vue3,写了一个轮播图,上代码,初级学习者,大佬勿喷,请大佬多多给指点宝贵经验。
于 2023-04-13 00:12:31 首次发布