- 基于wepy的项目需要实现小程序的列表懒加载
- 没找到合适的微信小程序懒加载插件,找的资料基本都是图片懒加载,于是自己实现
- 小程序API档:https://developers.weixin.qq.com/miniprogram/dev/framework/app-service/page.html
- 主要基于onReachBottom和onPullDownRefresh两个API,使用前请认真阅读文档
- wepy中动态传参需要用到.sync修饰符
- 已做防抖处理
一、子组件
<template>
<view class="ChildComponents " @tap="enterDetails">
{{itemData.title}}
{{itemData.content}}
</view>
</template>
<script>
import wepy from 'wepy';
export default class ChildComponents extends wepy.component {
props = {
itemData: {
type: Object,
default: {
id: '',
title: '标题',
content:'内容',
}
},
};
methods = {
enterDetails() {
let id=this.itemData.id*1;
if (!isNaN(id) && typeof id === 'number') {
wx.navigateTo({
url: 'miniProPage?id=' + id
});
}
}
};
}
</script>
二、父组件
<template>
<view class="gameList_emBox">
<repeat for="{{itemArray}}" item="item">
<ChildComponents class="GameListItem" :itemData.sync="item"></ChildComponents >
</repeat>
<view class='loadmore' hidden='{{isShowLoadmore}}'>
<view class='loading'></view>
<view class='loadmore_tips'>正在加载</view>
</view>
<view class="loadmore loadmore_line" hidden='{{!isShowNoDatasTips}}'>
<view class="loadmore_tips">我可是有底线哒!</view>
</view>
</view>
</template>
<script>
import wepy from 'wepy';
import ChildComponents from '../../components/ChildComponents ';
export default class parentComponent extends wepy.page {
config = {
navigationBarTitleText: '列表页面',
'enablePullDownRefresh': true,
};
components = { ChildComponents };
data = {
globalData: {},
page: 1,
num_pages:1,
loadedData: [],
isShowLoadmore: true,
isShowNoDatasTips: true,
endloading: false,
itemArray: [],
};
reviewpage(e) {
let _this = this;
let page = this.page;
_this.isShowLoadmore = false;
_this.isShowNoDatasTips = false;
_this.$apply();
wx.request({
url: this.globalData.baseUrl.reqUrl + '/xx/xx/xx/',
method: 'GET',
data: {
page: _this.page
},
success(res) {
if (!_this.loadedData.includes(_this.page)) {
_this.loadedData.push(_this.page);
_this.num_pages = res.data.num_pages;
if (res.data.num_pages + 1 == _this.page) {
_this.isShowNoDatasTips = true;
_this.endloading = true;
}
else {
let datas = res.data.data;
_this.itemArray = _this.itemArray.concat(datas);
_this.page += 1;
}
}
_this.isShowLoadmore = true;
_this.$apply();
}
});
};
onReachBottom() {
if (!this.data.endloading) {
this.reviewpage();
}
};
onPullDownRefresh() {
this.getData();
};
getData() {
let _this = this;
_this.page=1;
wx.request({
url: this.globalData.baseUrl.reqUrl + '/xx/xx/xx/',
data: {
page:_this.page,
},
success(res) {
_this.num_pages=res
_this.loadedData = [_this.page];.data.num_pages;
_this.page+=1;
_this.endloading = false;
_this.itemArray = res.data.data;
_this.$apply();
},
fail() {}
});
};
onShow(){
this.getData();
};
onLoad() {
this.globalData = wepy.$instance.globalData;
}
}
</script>