温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

vue.js如何编写一个轮播图

发布时间:2020-12-10 13:59:42 来源:亿速云 阅读:223 作者:小新 栏目:编程语言

这篇文章给大家分享的是有关vue.js如何编写一个轮播图的内容。小编觉得挺实用的,因此分享给大家做个参考。一起跟随小编过来看看吧。

vue.js写一个轮播图的方法:首先写出整体的框架;然后定义轮播图的数组,上传本地图片;最后通过改变自定义变量nowindex来改变轮播图的状态。

vue.js写一个轮播图的方法:

说下简单的思路,图片的轮播用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如何编写一个轮播图就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到吧!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI