vue 实现无限轮播_用vue写一个轮播图效果
輪播圖在網站中幾乎無處不在,占用地方少,交互性好。今天就來聊聊如何用vue實現一個輪播效果。
一、原理
在輪播圖數組dataList中,定義一個變量currentIndex = 0表示第一張圖片,默認渲染第一張圖片即dataList[currentIndex],然后獲取每張圖片的下標。點擊切換圖片時把當前圖片的下標賦值給currentIndex即可實現圖片切換顯示。
二、定義變量
data: {
dataList:["https://i1.mifile.cn/a4/xmad_15535933141925_ulkYv.jpg","https://i1.mifile.cn/a4/xmad_15532384207972_iJXSx.jpg","https://i1.mifile.cn/a4/xmad_15517939170939_oiXCK.jpg"],
currentIndex: 0, //默認顯示圖片
timer: null //定時器
}
三、模板渲染
- <
- {{index+1}}
- >
四、點擊小圓點切換圖片
{{index+1}}在li標簽里執行一個點擊函數,把當前下標值傳進來。點擊時設置currentIndex的值為當前的下標值。
methods: {
gotoPage(index) {
this.currentIndex = index;
}
}
五、左右按鈕切換圖片
<{{index+1}}>定義兩個變量作為參數prevIndex和nextIndex,利用計算屬性算出當前圖片的上一張圖片或者下一張圖片的下標(加1和減1操作)。
computed: {
//上一張
prevIndex() {
if(this.currentIndex == 0) {
return this.dataList.length - 1;
}else{
return this.currentIndex - 1;
}
},
//下一張
nextIndex() {
if(this.currentIndex == this.dataList.length - 1) {
return 0;
}else {
return this.currentIndex + 1;
}
}
}
六、定時器切換圖片
定義一個定時器,每X秒執行一次nextIndex()函數即可。
//定時器
runInv() {
this.timer = setInterval(() => {
this.gotoPage(this.nextIndex)
}, 1000)
}
鼠標經過清除定時器就不說了,使用clearInterval(this.timer)就可以了。
七、css樣式
* {
margin: 0;
padding: 0;
}
ul li {
list-style: none;
float: left;
width: 30px;
height: 40px;
line-height: 40px;
text-align: center;
cursor: pointer;
color: rgba(255,255,255,.8);
font-size: 14px;
}
.banner {
max-width: 1200px;
margin: 0 auto;
position: relative;
margin-top: 60px;
}
.banner img {
width: 100%;
display: block;
}
.banner .page {
background: rgba(0,0,0,.5);
position: absolute;
right: 0;
bottom: 0;
width: 100%;
}
.banner .page ul {
float: right;
}
.current {
color: #ff6700;
}
總結
以上是生活随笔為你收集整理的vue 实现无限轮播_用vue写一个轮播图效果的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: rmi 反序列化漏洞_IDEA动态调试(
- 下一篇: 5 加盐_小葱拌豆腐的5种做法,收藏起来