paging 工具类封装
/**
* 封装分页方法
*/
import {Http} from "./http";
class Paging {
//起始值 默认 0
start
//返回条数 默认 10
count
url
//请求对象
req
//是否锁定
locker = false
//是否有更多数据
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() {
let 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_num)
if (this.moreData) {
this.start += this.count
}
this._accumulator(paging.items)
return {
empty: false,
items: paging.items,
moreData: this.moreData,
accumulator: this.accumulator
}
}
//累加所有数据
_accumulator(items){
this.accumulator = this.accumulator.concat(items)
}
static _moreData(totalPage,pageNum){
return pageNum < totalPage - 1
}
// 获取请求对象 处理url 参数拼接
_getCurrentReq(){
let url = this.url
const params = `start=${this.start}&count=${this.count}`
if(url.includes('?')){
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
}
使用示例
import {Paging} from "../utils/paging";
class SpuPaging {
static getLatestPaging(){
//调用 paging
return new Paging({
url:'v1/spu/latest'
},3)
}
}
export {
SpuPaging
}
ps : http 工具类的封装
import {config} from "../config/config";
import {promisic} from "../miniprogram_npm/lin-ui/utils/util";
class Http {
static async request({url, data, method = "GET"}) {
const result = await promisic(wx.request)({
url: `${config.apiBaseUrl}${url}`,
data,
method,
header: {
appKey: config.appKey
}
})
return result.data
}
}
export {
Http
}