日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

uniapp/小程序 swiper組件無限數據滾動

作者:Terminal丶句點 更新時間: 2022-01-17 編程語言

最近開發的一個小程序中涉及一個答題頁面,打算使用小程序的swiper組件開發,題目可能數量過多,使用swiper一次性加載會造成卡頓,于是進行了一些優化

解決思路:頁面只展示3個swiper-item組件(小程序視頻輪播插件受到的啟發),每次輪播變化,都截取總數據里面的3條進行展示

觀察規律:畫了個簡單草圖,大家可以看下,每次輪播索引變化后,計算出當前索引、前一個索引值、后一個索引值,以及分別對應到數據列表上的索引和值

在這里插入圖片描述

代碼實現

<template>
  <view class="index-box">
    <swiper class="swipe" :circular="circular" :current="swipeActiveIndex" @change="swipeChange">
      <swiper-item v-for="(item, index) in swipeList" :key="index">
        <view class="swipe-item">{{ item }}</view>
      </swiper-item>
    </swiper>
  </view>
</template>
<script>
export default {
  data() {
    return {
      circular: true, // 是否可以循環滾動
      swipeActiveIndex: 0, // 當前輪播圖激活索引
      currentIndex: 0, // 當前展示數據在列表中的索引值
      swipeLength: 3, // 總的輪播圖數量
      dataList: [1, 2, 3, 4, 5, 6, 7] // 數據列表
    }
  },
  computed: {
    swipeList() {
      // 獲取當前值、下一個值、上一個值
      let currentValue = this.dataList[this.currentIndex]
      let nextValue = this.dataList[this.getDataIndex(this.currentIndex + 1)]
      let prevValue = this.dataList[this.getDataIndex(this.currentIndex - 1)]

      // 獲取當前輪播索引對應的值、下個索引對應的值、上個索引對應的值
      let list = new Array(3)
      list[this.swipeActiveIndex] = currentValue
      list[this.getSwipeIndex(this.swipeActiveIndex + 1)] = nextValue
      list[this.getSwipeIndex(this.swipeActiveIndex - 1)] = prevValue
      return list
    }
  },
  methods: {
    swipeChange(event) {
      let current = Number(event.detail.current)
      if ([1, 1 - this.swipeLength].includes(current - this.swipeActiveIndex)) {
      	// 向左滑動
        this.currentIndex = this.getDataIndex(this.currentIndex + 1)
      } else {
      	// 向右滑動
        this.currentIndex = this.getDataIndex(this.currentIndex - 1)
      }
      this.swipeActiveIndex = current
    },
    // 獲取當前數據列表的索引
    getDataIndex(index) {
      if (index < 0) {
        // 小于零,返回數據列表末尾索引
        return this.dataList.length - 1
      } else if (index >= this.dataList.length) {
        // 等于(或大于,一般不會)數據列表長度,返回數據首位索引
        return 0
      } else {
        return index
      }
    },
    getSwipeIndex(index) {
      if (index < 0) {
        return this.swipeLength - 1
      } else if (index >= this.swipeLength) {
        return 0
      } else {
        return index
      }
    }
  }
}
</script>
<style scoped lang="scss">
.index-box {
  width: 100%;

  .swipe {
    width: 100%;
    height: 300rpx;

    &-item {
      display: flex;
      width: 100%;
      height: 100%;
      font-size: 80rpx;
      color: #fff;
      background: #222;
      align-items: center;
      justify-content: center;
    }
  }
}
</style>

原文鏈接:https://blog.csdn.net/qq_40026668/article/details/122236668

欄目分類
最近更新