學習了vue.js也有一段時間了,做了個小demo來熟悉一下,很常見的demo,-------輪播圖,沒學vue之前的輪播圖用JavaScript或者jquery都非常簡單,發現用vue來寫也挺有意思的。說下簡單的思路,圖片的輪播用v-if或者v-show來代替原來的Js滑動,過度效果用transition可簡單實現,注意,滑動過程中是能看見兩張圖的,所以要用兩個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>
根據imgArray這個照片的數組渲染小圓點的數量,為span綁定on為小圓點點亮的狀態,照片的顯示隱藏通過自定義變量ifshow來顯示,nowindex則控制輪播對應的照片。
(2)輪播圖的數組,如果是本地的圖片,而且不放在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來改變輪播圖的狀態,要注意滑動的過程是能看見兩張圖的,所以在goto函數中設置了一個短暫的定時器,讓一張顯示另一張隱藏,分別加上不同的過度效果。
<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前端組件學習教程進行學習。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答