Generate url(key) from config
function createdUrl (config: any) {
return [
config.method,
config.url,
JSON.stringify(config.params),
JSON.stringify(config.data)
].join('&')}Copy the code
Axios intercept
// Request interceptor
axios.interceptors.request.use(config= > {
const url = createdUrl(config)
for (const k in store.state.axiosPromiseRecords) {
store.state.axiosPromiseRecords[k].uid === url && store.commit('removeRepeatAxiosPromiseRecord', k)
}
config.cancelToken = new axios.CancelToken((cancel: any) = > store.commit('addAxiosPromiseRecord', {
uid: url,
cancel
}))
// ...
return config
}, error= > Promise.reject(error))
// Response interceptor
axios.interceptors.response.use(response= > response, error= > {
if (axios.isCancel(error)) {
console.log('Route Cancellation request')
return new Promise(() = >{})}return Promise.reject(error)
})
Copy the code
Routing to intercept
// ...
router.beforeEach((to, from, next) = > {
toast.clear() // Clear all toasts
store.commit('clearAxiosPromiseRecords')
next()
})
// ...
Copy the code
store
// ...
state: {
// ...
axiosPromiseRecords: [] // Save the interface request record
},
mutations: {
// ...
addAxiosPromiseRecord(state: any, data: any) {
state.axiosPromiseRecords.push(data);
},
// Clear all axios requests
clearAxiosPromiseRecords(state: any) {
state.axiosPromiseRecords.length > 0 && state.axiosPromiseRecords.forEach((e: any) = > {
e && e.cancel()
})
state.axiosPromiseRecord = []
},
// Cancel the current duplicate AXIos request
removeRepeatAxiosPromiseRecord(state: any, index: number) {
// Cancel duplicate requests
state.axiosPromiseRecords[index].cancel();
// Delete this record from axiosPromiseRecords
state.axiosPromiseRecords.splice(index, 1); }}// ...
Copy the code