在vue中通過父子元件以及transition實現幻燈片
阿新 • • 發佈:2019-01-07
1.先在components資料夾中新建一個幻燈片元件slideShow.vue,然後在需要使用到幻燈片的頁面中import,註冊,便可在模板使用<slide-show>元件。
2。在使用<slide-show>時向幻燈片元件傳遞兩個引數,分別是照片資訊以及播放速度
<slide-show :slides="slides" :inv="slideSpeed"></slide-show>
slides和inv是要向幻燈片元件slideShow.vue傳遞的引數,在父元件的data()中return:
其中照片的路徑需要用require方法匯入
data(){ return { slideSpeed: 2000, slides: [ { src: require('../assets/slideShow/pic1.jpg'), title:'我', href: 'www.baidu.com' //href是點選圖片後跳轉的連結 }, { src: require('../assets/slideShow/pic2.jpg'), title:'愛', href: 'www.baidu.com' }, { src: require('../assets/slideShow/pic3.jpg'), title:'工', href: 'www.baidu.com' }, { src: require('../assets/slideShow/pic4.jpg'), title:'作', href: 'www.baidu.com' } ] } }
3。幻燈片子元件slideShow.vue中的的程式碼如下:
<template> <div class="slide-show" @mouseover="clearInv" @mouseout="runInv"> <div class="slide-img"> <a :href="slides[nowIndex].href"> <transition name="slide-trans"> <img v-if="isShow" :src="slides[nowIndex].src" /> </transition> <transition name="slide-trans-old"> <img v-if="!isShow" :src="slides[nowIndex].src" /> </transition> </a> </div> <h2>{{slides[nowIndex].title}}</h2> <ul class="slide-pages"> <li @click="goto(prevIndex)"><</li> <li v-for="(item,index) in slides" @click="goto(index)"> <a :class="{on:index===nowIndex}">{{index + 1}}</a> </li> <li @click="goto(nextIndex)">></li> </ul> </div> </template> <script> export default{ props: { slides: { type: Array, default: [] }, inv: { type:Number, default:1000 } }, data(){ return { nowIndex:0, isShow: true } }, computed: { prevIndex(){ if(this.nowIndex===0){ return this.slides.length-1 }else{ return this.nowIndex-1 } }, nextIndex(){ if (this.nowIndex===this.slides.length-1) { return 0 }else{ return this.nowIndex +1 } } }, methods: { goto(index){ this.isShow=false setTimeout(()=>{ this.isShow = true this.nowIndex = index },10) }, runInv(){ this.invId = setInterval(()=>{ this.goto(this.nextIndex) },this.inv) }, clearInv(){ clearInterval(this.invId) } }, mounted(){ this.runInv() console.log(this.slides) } } </script> <style scoped> .slide-trans-enter-active{ transition: all .5s; } .slide-trans-enter{ transform: translateX(900px); } .slide-trans-old-leave-active{ transition:all 0.5s; transform:translateX(-900px); } .slide-show{ position: relative; margin: 15px 15px 15px 0; width: 900px; height: 350px; overflow: hidden; } .slide-show h2{ position: absolute; width: 100%; height: 100%; color: #FFFFFF; background: #000; opacity: .5; bottom: 0; height: 30px; text-align: left; padding-left: 15px; } .slide-img{ width: 100%; } .slide-img img{ width: 100%; position: absolute; top: 0; } .slide-pages{ position: absolute; bottom: 10px; right: 15px; } .slide-pages li{ list-style: none; float: left; margin-right: 15px; color: #fff; cursor: pointer; } .on{ text-decoration: underline; } </style>
父元件傳遞過來的slides陣列以及inv用props接收,prevIndex和nextIndex用計算屬性實現使得上下翻頁不用重新定義函式,prevIndex和nextIndex會自動根據index而變化,整個頁面只用了一個goto函式實現幻燈片的效果。
4.頁面效果如下: