/** * 数据加载状态监听 * 重写_fetchData函数,添加自定义网络获取逻辑 * 调用_startLoad函数开始加载,_loadMore函数加载更多 * @param loadStatus 0: 加载完成; 1: 加载中; 2: 已全部加载; 3: 加载失败; */ export const useLoading = Behavior({ data: { cPage: 1, tPage: 1, perPage: 10, totalCount: 0, loadStatus: 0, pageLoading: false, needLoadMore: false, timeout: false, }, timeoutId: '', lastLoadStatus: 0, methods: { _startLoad() { wx.pageScrollTo({ scrollTop: 0, }); wx.stopPullDownRefresh(); this.setData({ cPage: 1, pageLoading: true, }); this._loading(); this._fetch(); }, _loadMore() { let { cPage, tPage } = this.data; if (cPage < tPage) { cPage++; this.setData({ cPage }); this._loading(); this._fetch(); } }, _pageLoadDone() { this.setData({ pageLoading: false }); }, _loadDone() { clearTimeout(this.timeoutId); this.setData({ loadStatus: 0 }); }, _loading() { if (this.data.lastLoadStatus != 1) { this.lastLoadStatus = 1; this.setData({ loadStatus: 1 }); clearTimeout(this.timeoutId); this.timeoutId = setTimeout(() => { this.setData({ loadStatus: 3, timeout: true, }); console.log('timeout'); }, 10000); } }, _loadEnd() { clearTimeout(this.timeoutId); this.setData({ loadStatus: 2 }); }, _loadFail() { clearTimeout(this.timeoutId); this.setData({ loadStatus: 3 }); }, _setPagination(cPage, tPage, totalCount) { this.setData({ cPage, tPage, totalCount }); }, _fetch() { if (typeof this._fetchData === 'function') { const promise = this._fetchData(this.data.cPage); if (!promise) return; promise .then(head => { if (head) { let cPage = head.currentPage ? parseInt(head.currentPage) : parseInt(head.page); let tPage = parseInt(head.totalPage); let totalCount = head.totalCount ? parseInt(head.totalCount) : 0; this._setPagination(cPage, tPage, totalCount); cPage < tPage ? this._loadDone() : this._loadEnd(); } else { this._loadEnd(); } }) .catch(err => { console.log(err); this._loadFail(); }) .finally(() => { this._pageLoadDone(); }); } }, /** * 在使用时重写此函数,编写网络获取函数 * @param {Number} cPage 当前分页 */ _fetchData(cPage) { return new Promise(); }, }, });