使用Vue制作图片轮播组件思路详解

2020-06-14 06:18:34易采站长站整理

修改move方法里的代码:

……


move(offset, direction) {
direction === -1 ? this.currentIndex++ : this.currentIndex--
if (this.currentIndex > 5) this.currentIndex = 1
if (this.currentIndex < 1) this.currentIndex = 5
this.distance = this.distance + offset * direction
if (this.distance < -3000) this.distance = -600
if (this.distance > -600) this.distance = -3000
}

上面的添加的三行代码很好理解,如果是点击右侧箭头,container就是向左移动, this.currentIndex 就是减1,反之就是加1。

效果:

 

可以看到,小圆点的切换效果已经出来了。

三、过渡动画

上面的代码已经实现了切换,但是没有动画效果,显的非常生硬,接下来就是给每个图片的切换过程添加过渡效果。

这个轮播组件笔者并没有使用Vue自带的class钩子,也没有直接使用css的transition属性,而是用慕课网原作者讲的setTimeout方法加递归来实现。

其实我也试过使用Vue的钩子,但是总有一些小问题解决不掉;比如下面找到的这个例子:例子

这个例子在过渡的边界上有一些问题,我也遇到了,而且还是时有时无。而如果使用css的transition过渡方法,在处理边界的无限滚动上总会在chrome浏览器上有一下闪动,即使添加了 -webkit-transform-style:preserve-3d; 和 -webkit-backface-visibility:hidden 也还是没用,而且要配合transition的 transitionend 事件对于IE浏览器的支持也不怎么好。

如果大家有看到更好的办法,请在评论中留言哦~

下面我们来写这个过渡效果,主要是改写:


methods:{
move(offset, direction) {
direction === -1 ? this.currentIndex++ : this.currentIndex--
if (this.currentIndex > 5) this.currentIndex = 1
if (this.currentIndex < 1) this.currentIndex = 5

const destination = this.distance + offset * direction
this.animate(destination, direction)
},
animate(des, direc) {
if ((direc === -1 && des < this.distance) || (direc === 1 && des > this.distance)) {
this.distance += 30 * direc
window.setTimeout(() => {
this.animate(des, direc)
}, 20)
} else {
this.distance = des
if (des < -3000) this.distance = -600
if (des > -600) this.distance = -3000
}
}
}

上面的代码是这个轮播我觉得最麻烦、也是最难理解的地方。

来理解一下:首先,我们对于move方法进行了改写,因为要一点点的移动,所以要先算出要移动到的目标距离。然后,我们写一个animate函数来实现这个过渡。这个animate函数接收两个参数,一个是要移动到的距离,另一个是方向。 如果我们点击了右侧的箭头,container要向左侧移动,要是没有移动到目标距离,就在 this.distance 减去一定的距离,如果减去后还是没有到达,在20毫米以后再调用这个 this.animate ,如此不断移动,就形成了过渡效果。而如果移动到了目标距离,那就将目标距离赋值给 this.distance ,然后再进行边界和无限滚动的判断。