LinUI学习10 使用Pagaing实现分页查询
一、在utils文件加下新建paging.js文件
二、编写paging.js
1、首先我们需要引入之前封装好的http公用请求(详情参照前面的笔记)
const {
Http
} = require("./http")
2、需要明确封装的paging需要 不关心细节、实例化、保存状态
3、我们需要一个锁来控制请求,进行防抖截流。
4、完整代码如下
const { Http } = require("./http") class Paging { start count req locker = false url moreData = true accumulator = [] constructor(req, count = 10, start = 0) { this.start = start this.count = count this.req = req this.url = req.url } async getMoreData() { if (!this.moreData) { return } if (!this._getLocker()) { return } const data = await this._actualGetData() this._releaseLocker() return data } async _actualGetData() { const req = this._getCurrentReq() let paging = await Http.request(req) if (!paging) { return null } if (paging.total === 0) { //一条数据都没有 return { empty: true, items: [], //当前请求回的数据 moreData: false, accumulator: [] //累加历史请求的数据 } } this.moreData = Paging._moreData(paging.total_Page, paging.page) if (this.moreData) { this.start += this.count } this._accumulate(paging.items) return { empty: false, items: paging.items, moreData: this.moreData, accumulator: this.accumulator } } static _moreData(totalPage, pageNum) { return pageNum < totalPage - 1 } //累加历史请求的数据 _accumulate(items) { this.accumulator = this.accumulator.concat(items) // 合并数组 } // 获取当前的请求对象 _getCurrentReq() { let url = this.url const params = `start=${this.start}&count=${this.count}` // url=v1/spu/latest + '?'+params // url=v1/spu/latest?other +'&'+params // 判断url内带不带问号 if (url.indexOf('?') !== -1) { url += '&' + params } else { url += '?' + params } this.req.url = url return this.req } _getLocker() { //查看锁的状态 if (this.locker) { return false } this.locker = true return true } _releaseLocker() { //复位 this.locker = false } } export { Paging }
三、使用paging.js
1、在model文件夹下新建suppaging.js 编写代码如下
const { Paging } = require("../utils/paging"); class SpuPaging { static getLatestPaging() { return new Paging({ url: `spu/latest` }, 3, 0) } } export { SpuPaging }
四、使用suppaging.js
示例:在home.js中使用
onLoad: async function (options) { this.initBottomSpuList() }, async initBottomSpuList(){ const paging = await SpuPaging.getLatestPaging() const data = await paging.getMoreData() if(!data){ return } },
这样就可以使用分页查询了