使用vue.js实现轮播的方法:首先使用“”将相应的元素包裹住;然后在“.imgShoudMove”中设置动画属性;最后采用Vue结合Css3来实现轮播图即可。
本教程操作环境:windows7系统、vue2.0&&css3版,Dell G3电脑,该方法适用于所有品牌电脑。
本文章采用Vue结合Css3来实现轮播图。
首先要了解的是Vue的动画原理。在vue中,如果我们要给元素设置动画效果,则需要使用一个将相应的元素包裹住,如下:
立即学习“前端免费学习笔记(深入)”;
@@##@@
登录后复制
之后,便可以在.imgShoudMove中设置动画属性了,如下:
.imgShouldMove-enter{ transition: all 0.5s; } .imgShouldMove-enter-active{ transform:translateX(900px); }
登录后复制
注意在HTML中,这里有一个v-if=”shoudShow”属性。shouldShow这个属性是在data(){}中设置的,当shouldShow从false–>true时(即img从无到突然出现时),
Vue动画原理将动画分为了 shouldShouldMove-enter 和 imgShouldMove-enter-active 两个阶段。
其中 shouldShouldMove-enter 表示动画开始的初始状态, imgShouldMove-enter-active 这表示动画的终止状态。而动画的触发则是通过if-show引起的。
示例:
HTML代码:
Script代码:export default { props:{ pics:{ type:Array, default:[] }, timeDelta:{ type:Number, default:2000 } }, data () { return { currentIndex:0, isShow:true, direction:'toleft' } }, computed:{ prevIndex(){ this.direction = 'toleft' if (this.currentIndex = this.pics.length - 1) { return 0 } return this.currentIndex + 1 } }, methods:{ goto(index){ this.isShow = false setTimeout(()=>{ this.isShow = true this.currentIndex = index },10) }, runInterval(){ this.direction = 'toright' this.timer = setInterval(()=>{ this.goto(this.nextIndex) },this.timeDelta) }, clearInv(){ clearInterval(this.timer) } }, mounted(){ this.runInterval() }}
登录后复制
与动画相关的css代码如下
.carousel-trans-toright-enter-active,.carousel-trans-toright-old-leave-active{ transition:all 0.5s; } .carousel-trans-toright-enter{ transform:translateX(940px); //新图片从右侧940px进入 } .carousel-trans-toright-old-leave-active{ transform:translateX(-940px); //老图片向左侧940px出去 } .carousel-trans-toleft-enter-active,.carousel-trans-toleft-old-leave-active{ transition:all 0.5s; } .carousel-trans-toleft-enter{ transform:translateX(-940px); //新图片从右侧940px进入 } .carousel-trans-toleft-old-leave-active{ transform:translateX(940px); //老图片向左侧940px出去 }
登录后复制
注意:对于需要放在里面,需要设置为position:relative; 而
必须设置为position:absolute; 这步非常非常重要,否则每次莫名其妙的总是只有一张图片显示。
在每次切换的时候,都要触发goto()方法,将this.isShow先置false,10毫秒后,this.isShow置true。这时,html中的被触发,它与css相结合触发动画效果,持续时间为css属性中的transition所定的0.5s。
在向前、向后切换的时候,使用到了计算属性,在div.prevBtn以及div.nextBtn上,我们作了点击事件绑定,触发方法goto(),而传入的正是计算属性prevIndex, @click=”goto(prevIndex)”
计算属性的设定方法如下:
computed:{ prevIndex(){ //经过一番计算过程得出result return result //这个值即中的prevIndex } },
登录后复制
每隔2秒自动滑动时,我们向left滑动,在data中,设定了变量 direction ,它的值要么为字符串’toleft’,要么为’toright’。
我们在计算属性中对 this.direction 进行了设置,并在中对相应的name进行了字符串拼接,如下
登录后复制
在vue中,除了class和style可以传入对象、数组,其他的属性绑定必须进行字符串拼接。
推荐:《vue教程》
以上就是使用vue.js如何实现轮播的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/3021258.html