这边用swiper实现一个日历组件,swiper是开启了循环的。
但是我看文档中并没有介绍通过组件方法控制轮播图滚动
swiper文档
类似这样
this.$refs.swiper.prev()
this.$refs.swiper.next()
this.$refs.swiper.gotoPage()
我通过绑定current属性,手动改变current的值来触发swiper滑动,但是存在问题。
比如一个3页的swiper,0 1 2,current = 2时,如果我设置current = 0,swiper会向左滑动两格到达0,而我期望的效果是向右滑动一格到达0。
我查了一下社区好像并没有相关的问题,所以想问一问有什么解决办法。
---------------------------------- 补充测试案例--------------------------------------------
我写了一个简单的测试代码复现了问题
<template>
<view>
<swiper style="height: 200px; border: 1px solid black; margin-top: 60px;" :current="current" circular @change="changeHandler">
<swiper-item>第一页</swiper-item>
<swiper-item>第二页</swiper-item>
<swiper-item>第三页</swiper-item>
</swiper>
<button @click="prevHandler">后退</button>
<button @click="nextHandler">前进</button>
</view>
</template>
<script>
const LEN = 3
export default {
data () {
return {
current: 1
}
},
methods: {
// 使轮播图右滑一格
next () {
this.current = (this.current + 1) % LEN
},
// 使轮播图左滑一格
prev () {
this.current = (this.current - 1 + LEN) % LEN
},
prevHandler () {
this.prev()
},
nextHandler () {
this.next()
},
changeHandler (e) {
console.log(e, e.detail.current)
}
},
mounted () {
}
}
</script>
测试的效果我上传了视频
可以看出,小程序的效果是我所期望的,但是H5端却无视轮播循环,向左滑了2格,APP的表现与H5一致,因为是真机测试(华为 Mate30),我没有录。
现在H5端可以这样填坑,但是APP获取不到Vue对象,这个方法也没法用。
// #ifdef H5
// 这里必须涉及到源码,否则会无法达到循环滚动的效果
const swiper = this.$refs.swiper
const newVal = swiper._normalizeCurrentValue(this.curIndex + offset)
// 指定动画行为,否则当滑到循环处时,会出现反向滑动的BUG
swiper.currentChangeSource = 'autoplay'
// 滑动索引跟进
swiper.currentSync = newVal
// 播放滑动动画,第三个参数决定了滑动方向,大于0时右滑,小于0时左滑
swiper._animateViewport(newVal, '', offset)
this.swiperIndex = newVal
// #endif
8***@qq.com (作者)
确实是APP和H5的表现和小程序不一致,我上传了简单的测试代码和效果视频。
后退(从0到2)的循环在三端都是正常的,就是前进(从2到0)存在问题
2020-05-02 10:46