前端我的项目中常常遇到申请输出查找场景,防抖与截流很好解决了频繁输出问题,然而不能解决最先发动申请后果后返回,笼罩了最初一次的搜寻后果,导致搜寻后果不正确。我总结一下本人罕用的两种办法。
- 应用工夫戳来过滤返回后果,如果申请回调函数中的工夫戳小于以后工夫戳则返回,阐明曾经解决了之后的申请后果了,这个申请过期了。
// 近程搜寻商品 searchGoods(data) { if (!data) { return } if (this.isRemote) { const reqCount = new Date().getTime() this.OrderInquireQuerySpuAndUnit({ keyWord: data }).then(res => { if (this.reqCount < currentReqCount) { return } if (res.data) { if (res.data.length > 0) { this.goodsList = res.data } } }).catch(err => { console.log(err) }).finally(() => { this.currentReqCount = reqCount }) } },
- 基于axios封装对立的申请办法,前面发动的申请会勾销之前期待返回后果的申请,须要多传一个cancelTokenPath,示意以后同一个输出组件发动的申请
export const getRequest = param => { const { cancelTokenPath, ...restQuery } = (param && param.query) || {} // cancelTokenPath是为了防止页面中多处申请的同一个接,导致谬误的勾销 if (cancelTokenPath) { const CancelToken = axios.CancelToken const source = CancelToken.source() if (store[cancelTokenPath]) { store[cancelTokenPath].cancel('Canceled by the last request') } store[cancelTokenPath] = source } return new Promise((resolve, reject) => { Vue.axios .get(param.url, { params: restQuery || {}, headers: param.headers || {}, cancelToken: cancelTokenPath && store[cancelTokenPath].token }) .then(res => { resolve(res) }) .catch(err => { reject(err) }) })}