最近开发的一个小程序中涉及一个答题页面,打算使用小程序的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]