Front-end projects often encounter request input search scenarios. Anti-shake and interception can handle the problem of frequent input very well, but they cannot solve the problem of returning the result of the first request, covering the last search result, resulting in incorrect search results. I summarize the two methods that I commonly use.
- Use the timestamp to filter the returned result. If the timestamp in the request callback function is less than the current timestamp, it will be returned, indicating that the subsequent request result has been processed, and the request is outdated.
// 远程搜索商品
searchGoods(data) {
if (!data) {
return
}
if (this.isRemote) {
const reqCount = new Date().getTime()
this.OrderInquireQuerySpuAndUnit({ keyWord: data }).then(res => {
if (reqCount < this.currentReqCount) {
return
}
if (res.data) {
if (res.data.length > 0) {
this.goodsList = res.data
}
}
}).catch(err => {
console.log(err)
}).finally(() => {
this.currentReqCount = reqCount
})
}
},
- Based on the unified request method encapsulated by axios, the request initiated later will cancel the request that was waiting for the result to be returned. One more cancelTokenPath needs to be passed, indicating the request initiated by the same input component.
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)
})
})
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。