小程序swiper组件用箭头控制无法衔接

2019-12-03  本文已影响0人  紫气楠楠

问题描述

小程序组件swiper左右滑动,自动轮播时circular衔接效果都是没有问题的,但当我们用左右箭头模拟轮播的时候,衔接效果却失效了,问题出在哪里?
我们来看下面一段代码:

//wxml
 <view class='swiperbox'>
    <swiper class='swiper-content' circular="true" style="height:{{Height}};" current='{{current}}' circular='true'
    bindchange="demo" autoplay='{{autoplay}}' interval="{{interval}}">
    <swiper-item wx:for="{{swiperData}}" wx:key="index">
        <image src='{{item}}'></image>
        <view class='page'>{{index+1}}/{{swiperData.length}}</view>
    </swiper-item>
    </swiper>
</view>
<view class='bottom'>
    <view class='btn-left' bindtap='prev'><image src='{{AppImg.pptpageleft}}'></image></view>
    <view class='btn-right' bindtap='next'><image src='{{AppImg.pptpageright}}'></image></view>
</view>

//js
 data: {
    AppImg: util.AppImg,
    Height: '530rpx',
    swiperData:[
      '../img/demo.png',
      '../img/demo.png',
      '../img/demo.png'
    ],
    current:0,
    interval: 100,
    autoplay: false,
  },
//下一页
 next:function(){
    let count = this.data.current
    count = count < (this.data.swiperData.length - 1) ? count + 1 : 0;
    this.setData({
      current:count
    })
  },
//current改变时触发的change事件
  demo:function(e){
    console.log(e.detail.source)
  },

问题分析

上面代码中,滑动时source(来源)打印的是touch,自动轮播时打印的是autoplay,但我们点击下一页时,打印的却是空,那么,我们猜测是swiper组件只内置了滑动与自动轮播的机制,没有点击下一页的机制,
当我们用箭头模拟时,swiper无法在内部找到source来源,所以无法衔接滑动了,既然知道了是source的原因,那么我们要考虑的就是如何模拟swiper内部机制了,
那如何去模拟呢,这就要从autoplay这个内置属性搞事情了。

思路:将autoplay默认为false,点击下一页,将autoplay重置为true,检测bindchange事件的source来源,如果是autoplay,就做动态关闭处理将其设置为false,每一变化都将当前的current记录下来(不记录的话点击上一页跳转位置会错乱)

 data: {
    AppImg: util.AppImg,
    Height: '530rpx',
    swiperData:[
      '../img/demo.png',
      '../img/demo.png',
      '../img/demo.png'
    ],
    current:0,
    interval: 100,
    autoplay: false,
  },
  //上一页
  prev:function(){
    let count = this.data.current
    count = count>0?count-1:this.data.swiperData.length-1
    this.setData({
      current:count
    })
  },
  //下一页
  next:function(){
    this.setData({
      autoplay:true
    })
  },
  //当前页current改变时触发的change事件
  demo:function(e){
    console.log(e.detail.source)
    if(e.detail.source=='autoplay'){
      this.setData({
        autoplay:false
      })
    }
     this.setData({
      current: e.detail.current//记录下当前的滑块位置
    })
  },
上一篇 下一篇

猜你喜欢

热点阅读