swiper组件取消自动播放,获取当前的current出现bug
发布于 5 年前 作者 syao 19655 次浏览 来自 问答

1页面

  <checkbox-group bindchange=“checkboxChange”>
        <checkbox value=“1” checked="" />自动播放
   </checkbox-group>

<swiper autoplay="{{autoplay}}" bindchange=“handleSwiper” interval=“5000” current="{{current}}" circular=“true”>
    <swiper-item wx:key=“unique” wx:for="{{dataList}}" >
      <view>
        <text>{{ item.title }}</text>
      </view>
    </swiper-item>
  </swiper>

2 js

 Page({
  data: {
    autoplay: false,
    current: 0
  },

  /**
   *监听checkbox事件
   */
  checkboxChange: function (e) {
    var that = this
      that.setData({
        autoplay: false
      })
    }
    console.log(that.data.current)
  }

  handleSwiper: function(e){
    var that = this
    that.setData({
       current: e.detail.current
    })
  }

3问题描述: 取消自动播放,获取当前current跟Wxml中的current不一致,即是有时候出现执行了checkbox事件,handleSwiper还会执行handleSwiper事件。

6 回复

这个没什么好办法,只能具体问题具体处理了,比如在你的这个例子里面,在handleSwiper中检查一下that.data.autoplay,如果是false的话就可以认为checkboxChange是已经执行过了的。

在handleSwiper中检查一下that.data.autoplay,如果使用手动切换的话,that.data.autoplay本身就是为false,还是需要执行handleSwiper里面的代码来展示当前current的数据

感谢反馈。

Q: current不一致?

A: 无论取消自动播放与否,data.current永远是使用setData设置的current,而不是swiper实际的current。

Q: checkbox事件后仍有可能触发handleSwiper?

A: 是的。这是因为JS运行于一个独立线程。从在JS中使用setData设置current值,到current值被应用到swiper,会有一小段时差。这段时间内,swiper仍可能触发change事件。

我已尝试这种方法,这样会带出另外一个问题的。

我这只是说个方向而已,具体怎么做还得根据你具体的情况来决定哦。

对于这个一小段时差,如何处理这个swiper仍可能触发change事件。

回到顶部