微信小程序答题页 swiper分页 极简
发布于 2 年前 作者 min88 3268 次浏览 来自 分享

因为最近要写个做题页面,要求左右滑动切换页面。题目数量三位数会导致swiper卡顿严重,找了下相关文章没有发现合适的,就自己写了下。

实现功能

1、可以加载大量数据

2、跳转任意index

3、实现代码简单,方便复用

直接帖代码

// pages/swiper/swiper.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    dataList: [], //实际数据
    list: [], //展示数据
    currentIndex: 0//真实的index
    current: 0//swiper当前的index
    recordCurrent: 0//swiper上次的index
    duration: 300 //动画时常
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    for (let i = 0; i < 1000; ++i) {
      this.data.dataList.push(i)
    }
    this.setData({
      dataList: this.data.dataList
    })
    this.upSwiper(0)
  },
  animationfinish({
    detail
  }) {
    // 用户滑动
    if (detail.source == "touch") {
      // 滑动后的index
      this.upSwiper(this.data.currentIndex + detail.current - this.data.recordCurrent)
    }
  },
  upSwiper(index) {
    // 防止越界
    if (index < 0 || index >= this.data.dataList.length) {
      return
    }
    this.setData({
      currentIndex: index
    })
    // 更新数据
    let list = []
    for (let i = this.data.currentIndex - 1; i <= this.data.currentIndex + 1; ++i) {
      let item = this.data.dataList[i]
      if (typeof (item) !== "undefined") {
        list.push(item)
      }
    }
    let current = 0;
    // 只要不是第一个页面 current都是1 
    if (index != 0) {
      current = 1
    }
    // 取消动画
    this.setData({
      duration: 0
    })
    // current 和 list要同时更新,不然数据会闪
    this.setData({
      current: current,
      recordCurrent: current,
      duration: 300,
      list
    })
  },
  tap(ev) {
    let index = ev.currentTarget.dataset.index
    this.upSwiper(index)
  }
})
<!--pages/swiper/swiper.wxml-->
<swiper id="swiper" current="{{current}}" duration="{{duration}}" bindanimationfinish="animationfinish">
  <swiper-item wx:for="{{list}}" wx:for-item="ee">
    <view wx:for="{{20}}">{{ee}}</view>
  </swiper-item>
</swiper>

<view class="but-z"><button catchtap="tap" data-index="{{0}}">0</button> <button catchtap="tap" data-index="{{5}}">5</button> <button catchtap="tap" data-index="{{dataList.length-1}}">{{dataList.length-1}}</button>
</view>
/* pages/swiper/swiper.wxss */
#swiper {
  width: 100vw;
  height: 100vh;
}

.but-z {
  position: fixed;
  bottom: 20px;
  height: 40px;
  width: 100vw;
  display: flex
}

button {
  background-color: red;
  width: 100rpx !important;
  text-align: center;
}
1 回复

非常感谢收藏了

回到顶部