需求:为解决首页一次性加载数据量过大的情况,使用虚拟加载,使用 swiper滚动,在下滑时去加载图片,当前展示一张图片,上下各缓冲一张图片,到最后一条数据时请求接口加载更多的数据。
template部分
<swiper vertical circular
:style="{ height: height + 'px' }"
:current="swiperActiveIndex" @change="swiperChange">
<swiper-item v-for="item in swiperList" :key="item.id" :style="{ height: height + 'px' }">
{{ item.title }}
<image :src="item.image"></image>
</swiper-item>
</swiper>
data部分,定义数据
data() {
return {
height: '',
swiperList: [], //截取的数组
swiperActiveIndex: 0, //当前滑块索引
currentIndex: 0, //当前图片索引
goodsParams: {
current: '1',
size: 10
},
goods: [] //全部数据
};
},
获取页面高度
onLoad() {
this.height = uni.getSystemInfoSync().windowHeight;
this.getgoodsPage();
},
下面是method部分,请求数据,处理数据
getgoodsPage() {
let res = goodsPage(this.goodsParams);
let { records } = res.data;
this.goods =[...this.goods, ...this.records];
this.getShowList();
},
getShowList() {
let current = this.goods[this.currentIndex]; //当前展示的
let nextSibling = this.goods[this.getGoodIndex(this.currentIndex + 1)]; //当前的下一个
let preSibling = this.goods[this.getGoodIndex(this.currentIndex - 1)]; //当前的上一个
this.swiperList = new Array(3);
this.swiperList[this.swiperActiveIndex] = current; //当前的滑块
this.swiperList[this.getActiveIndex(this.swiperActiveIndex + 1)] = nextSibling;
this.swiperList[this.getActiveIndex(this.swiperActiveIndex - 1)] = preSibling;
},
对0的上一张的索引进行处理
getGoodIndex(index) {
if (index < 0) {
return this.goods.length - 1;
} else if (index >= this.goods.length) {
return 0;
} else {
return index;
}
},
getActiveIndex(index) {
if (index < 0) {
return this.swiperList.length - 1;
} else if (index >= this.swiperList.length) {
return 0;
} else {
return index;
}
},
滑动时将处理的数据
swiperChange(e) {
let current = e.detail.current;
//1或-2向下滑动否则就是向上
if ([1, 1 - this.swiperList.length].includes(current - this.swiperActiveIndex)) {
this.currentIndex = this.getGoodIndex(this.currentIndex + 1);
} else {
this.currentIndex = this.getGoodIndex(this.currentIndex - 1);
if (this.currentIndex === this.goods.length) {
this.goodsParams.current += 1;
this.getgoodsPage();
}
}
this.swiperActiveIndex = current;
this.getShowList();
}