根据config生成url(key)
function createdUrl (config: any) {
return [
config.method,
config.url,
JSON.stringify(config.params),
JSON.stringify(config.data)
].join('&')
}
axios拦截
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))
axios.interceptors.response.use(response => response, error => {
if (axios.isCancel(error)) {
console.log('路由取消请求')
return new Promise(() => {})
}
return Promise.reject(error)
})
路由拦截
router.beforeEach((to, from, next) => {
toast.clear()
store.commit('clearAxiosPromiseRecords')
next()
})
store
state: {
axiosPromiseRecords: []
},
mutations: {
addAxiosPromiseRecord(state: any, data: any) {
state.axiosPromiseRecords.push(data);
},
clearAxiosPromiseRecords(state: any) {
state.axiosPromiseRecords.length > 0 && state.axiosPromiseRecords.forEach((e: any) => {
e && e.cancel()
})
state.axiosPromiseRecord = []
},
removeRepeatAxiosPromiseRecord(state: any, index: number) {
state.axiosPromiseRecords[index].cancel();
state.axiosPromiseRecords.splice(index, 1);
}
}