vue axios路由跳轉取消所有請求 和 防止重復請求


直接上干貨

在發送第二次請求的時候如果第一次請求還未返回,則取消第一次請求,以保證后發送的請求返回的數據不會被先發送的請求覆蓋。

或者是跳轉路由的時候取消還未返回的請求

第一步: axios 怎么取消:

const CancelToken = axios.CancelToken;
let cancel;
axios.get('/user/12345', {
cancelToken: new CancelToken(function executor(c) {
// An executor function receives a cancel function as a parameter
cancel = c;
})
});

第二步: 這是取消一個axios 如果是多個呢?那么我們就需要有個地方給存下來
vuex
state: {
// axios取消請求
axiosPromiseCancel: [],
}
第三步: axios 攔截器axios.js
import store from './store';
const CancelToken = axios.CancelToken;

let cancel;
// 防止重復請求
let removePending = (config) => {
for (let k in store.state['axiosPromiseCancel']) {
if (store.state['axiosPromiseCancel'][k].u === config.url + '&' + config.method) { //當前請求在數組中存在時執行函數體
store.state['axiosPromiseCancel'][k].f(); //執行取消操作
store.state['axiosPromiseCancel'].splice(k, 1); //把這條記錄從數組中移除
}
}
};
axios.interceptors.request.use(config=>{
// 這個是 取消重點
removePending(config);
config.cancelToken = new CancelToken((cancel) => {
store.state['axiosPromiseCancel'].push({ u: config.url + '&' + config.method, f: cancel });
});
  return config;
});
axios.interceptors.response.use(res=>{
removePending(res.config);
  // do something...
},error=>{
if (axios.isCancel(error)) {
// 為了終結promise鏈 就是實際請求 不會走到.catch(rej=>{});這樣就不會觸發錯誤提示之類了。
return new Promise(() => {});
}else{
return Promise.reject(error)
}});

第四步: 就是在router 里做取消動作了 router.js

import store from './store';
router.beforeEach((to, from, next) => {
if(store.state['axiosPromiseCancel'].length > 0) {
store.state['axiosPromiseCancel'].forEach(e => {
e && e.f()
});
}
store.state['axiosPromiseCancel'] = [];

})


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM