let pending = [] //聲明一個數組用於存儲每個ajax請求的取消函數和ajax標識
let cancelToken = axios.CancelToken
let removePending = config => {
for (let p in pending) {
if (pending[p].u === config.url + '&' + config.method) {
//當前請求在數組中存在時執行函數體
pending[p].f() //執行取消操作
pending.splice(p, 1) //把這條記錄從數組中移除
}
}
}
//添加請求攔截器
axios.interceptors.request.use(
config => {
removePending(config) //在一個ajax發送前執行一下取消操作
config.cancelToken = new cancelToken(c => {
// 這里的ajax標識我是用請求地址&請求方式拼接的字符串,當然你可以選擇其他的一些方式
pending.push({ u: config.url + '&' + config.method, f: c })
})
return config
},
error => {
return Promise.reject(error)
}
)
//添加響應攔截器
axios.interceptors.response.use(
response => {
removePending(response.config) //在一個ajax響應后再執行一下取消操作,把已經完成的請求從pending中移除
return response
},
error => {
return { data: {} } // 返回一個空對象,主要是防止控制台報錯
}
)