今天要做一個輪播圖,網上找了一圈都不滿意,自己寫了個.
效果如下:
圖片可自行配置,始終顯示6(改v-for後的列表可以控制數量)張;
核心代碼:
<ul v-on:mouseout="move()" v-on:mouseover="stopmove()">
<i @click="left()" class="el-icon-arrow-left"></i>
<li :key="index" v-for="index in [0,1,2,3,4,5]">
<img :src="changeImage(index)" @click="goToOneMap(index)" alt=""/>
</li>
<i @click="right()" class="el-icon-arrow-right"></i>
</ul>
//點擊按鈕左移
left() {
this.currentImageIndex--;
if (this.currentImageIndex < 0) {
this.currentImageIndex = this.pictures.length - 1
}
},
//點擊按鈕右移
right() {
this.currentImageIndex++;
if (this.currentImageIndex > this.pictures.length - 1) {
this.currentImageIndex = 0
}
},
原理蠻簡單的,根據vue的特性通過方法返回圖片地址,用一個變量記錄移動的下標位數,一輪就重置.
完整組件代碼,可自動切換,手動切換,帶參數轉跳:
<template>
<ul v-on:mouseout="move()" v-on:mouseover="stopmove()">
<i @click="left()" class="el-icon-arrow-left"></i>
<li :key="index" v-for="index in [0,1,2,3,4,5]">
<img :src="changeImage(index)" @click="goToOneMap(index)" alt=""/>
</li>
<i @click="right()" class="el-icon-arrow-right"></i>
</ul>
</template>
<script>
export default {
name: "Slideshow",
data() {
return {
//這裏配置圖片,變量我定義在了其他位置.格式如下
//var slidePictures = [
// {
// documentName: '雲南瓦片數據',
// img: '../../static/images/home1.jpg',
// },
// {
// documentName: '',
// img: '../../static/images/home2.png',
// }]
pictures: slidePictures,
currentImageIndex: 0
}
},
created() {
this.move()
},
methods: {
changeImage(index) {
if (index - this.currentImageIndex >= 0) {
return this.pictures[index - this.currentImageIndex].img
} else {
return this.pictures[index - this.currentImageIndex + this.pictures.length].img
}
},
//移動
move() {
this.timer = setInterval(this.starmove, 2500)
},
//開始移動
starmove() {
this.currentImageIndex--;
if (this.currentImageIndex < 0) {
this.currentImageIndex = this.pictures.length - 1
}
},
//鼠標懸停時停止移動
stopmove() {
clearInterval(this.timer)
},
//點擊按鈕左移
left() {
this.currentImageIndex--;
if (this.currentImageIndex < 0) {
this.currentImageIndex = this.pictures.length - 1
}
},
//點擊按鈕右移
right() {
this.currentImageIndex++;
if (this.currentImageIndex > this.pictures.length - 1) {
this.currentImageIndex = 0
}
},
goToOneMap(index) {
var documentName = "";
if (index - this.currentImageIndex >= 0) {
documentName = this.pictures[index - this.currentImageIndex].documentName
} else {
documentName = this.pictures[index - this.currentImageIndex + this.pictures.length].documentName
}
this.$router.push({
path: "index",
query: {
documentName: documentName
}
})
}
},
}
</script>
<style scoped>
ul {
display: flex;
flex-direction: row;
}
ul li {
list-style: none;
width: 15%;
margin: 0 auto;
height: 200px;
padding: 10px;
}
ul li img {
width: 100%;
height: 100%;
}
i {
color: white;
vertical-align: bottom;
margin-top: 88px;
font-size: 24px;
cursor: pointer;
}
</style>