/** * 接口请求缓存 * 1、urlPath变换,清空缓存 * 2、参数变化重新请求 */ interface IDelStoreItem { paramsJson?: string, data?: any, callbackList: Function[] } interface ICacheReq { delStoreFc: Function[], delStore: Function, reg: Function } const cacheReq: ICacheReq = { // 重制缓存Fc列表 delStoreFc: [], // 清空缓存列表 delStore() { this.delStoreFc.forEach(item => item()) }, // 注册 reg(Fc) { let cacheList: IDelStoreItem[] = [] // 缓存数据 this.delStoreFc.push(() => { cacheList = [] }) return (callback: any = null, params = {}, cache = true) => { return new Promise((resolve: Function) => { if (callback) resolve() else callback = resolve const crtParamsJson = JSON.stringify(params) // 查找缓存列表 let find: any = cache && cacheList.find(item => { return item.paramsJson === crtParamsJson }) if (find?.data) { return callback(find.data) } else if (!find) { cacheList.push({ paramsJson: crtParamsJson, data: null, callbackList: [callback] }) find = cacheList[cacheList.length - 1] } else { find.callbackList.push(callback) } if (find.callbackList.length > 1) return Fc((data) => { find.data = data find.callbackList.forEach(back => { back(data) }) find.callbackList = [] }, params) }) } } } export default cacheReq