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

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

},
{
img:'../../static/images/4.jpg'
},
{
img:'../../static/images/5.jpg'
}
],
currentIndex:1,
distance:-600,
transitionEnd: true
}
},
computed:{
containerStyle() {
return {
transform:`translate3d(${this.distance}px, 0, 0)`
}
}
},
methods:{
move(offset, direction) {
if (!this.transitionEnd) return
this.transitionEnd = false
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 (this.temp) {
window.clearInterval(this.temp)
this.temp = null
}
this.temp = window.setInterval(() => {
if ((direc === -1 && des < this.distance) || (direc === 1 && des > this.distance)) {
this.distance += 30 * direc
} else {
this.transitionEnd = true
window.clearInterval(this.temp)
this.distance = des
if (des < -3000) this.distance = -600
if (des > -600) this.distance = -3000
}
}, 20)
}
}
}
</script>

接下来我们要实现点击下面的小圆点来实现过渡和图片切换。


<ul class="dots">
<li v-for="(dot, i) in sliders" :key="i"
:class="{dotted: i === (currentIndex-1)}"
@click = jump(i+1)>
</li>
</ul>

在点击小圆点的时候我们调用 jump 函数,并将索引 i+1 传给它。 这里需要特别注意,小圆点的索引和图片对应的索引不一致,图片共7张,而5个小圆点对应的是图片中中间的5张,所以我们才传 i+1 。


jump(index) {
const direction = index - this.currentIndex >= 0 ? -1 : 1 //获取滑动方向
const offset = Math.abs(index - this.currentIndex) * 600 //获取滑动距离
this.move(offset, direction)
}

上面的代码有一个问题,在jump函数里调用move方法,move里对于currentIndex的都是 +1 ,而点击小圆点可能是将 currentIndex 加或者减好多个,所以要对move里的代码修改下:


direction === -1 ? this.currentIndex += offset/600 : this.currentIndex -= offset/600

改一行,根据offset算出currentIndex就行了。

但是又有一个问题,长距离切换速度太慢,如下:

 

所以我们需要控制一下速度,让滑动一张图片耗费的时间和滑动多张图片耗费的时间一样,给move和animate函数添加一个speed参数,还要再算一下: