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.页面效果如下: