vue.js實現(xiàn)簡單輪播圖效果
學習了vue.js也有一段時間了,做了個小demo來熟悉一下,很常見的demo,-------輪播圖,沒學vue之前的輪播圖用JavaScript或者jquery都非常簡單,發(fā)現(xiàn)用vue來寫也挺有意思的。說下簡單的思路,圖片的輪播用v-if或者v-show來代替原來的Js滑動,過度效果用transition可簡單實現(xiàn),注意,滑動過程中是能看見兩張圖的,所以要用兩個transition。
(1)先寫出整體的框架
<template> <div class="slide-show"> <div class="slide-img"> <transition name="slide-trans" > <img v-if='ifshow' :src='imgArray[nowindex]'> </transition> <transition name="slide-trans-old"> <img v-if="!ifshow" :src="imgArray[nowindex]"> </transition> <ul class="slide-pages"> <li v-for="(item,index) in imgArray"> <span :class="{on :index===nowindex}" @click="goto(index)"></span> </li> </ul> </div> </div> </template>
根據(jù)imgArray這個照片的數(shù)組渲染小圓點的數(shù)量,為span綁定on為小圓點點亮的狀態(tài),照片的顯示隱藏通過自定義變量ifshow來顯示,nowindex則控制輪播對應的照片。
(2)輪播圖的數(shù)組,如果是本地的圖片,而且不放在static文件下的,請用require圈上路徑,否則路徑會報錯。如果是從后臺服務器獲取的則不需要。
data(){ return{ imgArray: [ require('../../img/item_01.png'), require('../../img/item_02.png'), require('../../img/item_03.png'), require('../../img/item_04.png') ] } }
(3)主要就是通過改變自定義變量nowindex來改變輪播圖的狀態(tài),要注意滑動的過程是能看見兩張圖的,所以在goto函數(shù)中設置了一個短暫的定時器,讓一張顯示另一張隱藏,分別加上不同的過度效果。
<script type="text/javascript"> export default { props:{ imgArray:{ type:Array, default:[] } }, data() { return { ifshow:true, nowindex:0, } }, created(){ this.timerun() }, computed:{ nextindex(){ if(this.nowindex === this.imgArray.length -1){ return 0 }else{ return this.nowindex + 1 } } }, methods: { goto(index){ let that = this; this.ifshow = false; setTimeout(function(){ that.ifshow = true; that.nowindex = index; },100) }, timerun(){ let that = this; setInterval(function(){ that.goto(that.nextindex) },2000) } } } </script>
到這里,這個簡單的輪播圖就到此結束了。
關于vue.js的學習教程,請大家點擊專題vue.js組件學習教程、Vue.js前端組件學習教程進行學習。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
vue組件vue-treeselect箭頭和叉圖標變大問題及解決
這篇文章主要介紹了vue組件vue-treeselect箭頭和叉圖標變大問題及解決方案,具有很好的參考價值,希望對大家有所幫助。2022-07-07vue keep-alive 動態(tài)刪除組件緩存的例子
今天小編就為大家分享一篇vue keep-alive 動態(tài)刪除組件緩存的例子,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11使用vue打包時vendor文件過大或者是app.js文件很大的問題
這篇文章主要介紹了使用vue打包時vendor文件過大或者是app.js文件很大問題的解決方法,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2018-06-06