重複點擊或者多tab標籤使用一個視圖等(固然也能夠用加載中或者透明背景禁止請求中再次點擊)ios
來自於互聯網axios
let pending = []; //聲明一個數組用於存儲每一個請求的取消函數和axios標識 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); } } } // http請求攔截器 axios.interceptors.request.use(config => { removePending(config); //在一個axios發送前執行一下取消操做 config.cancelToken = new cancelToken((c)=>{ // 這裏的axios標識我是用請求地址&請求方式拼接的字符串,固然你能夠選擇其餘的一些方式 pending.push({ u: config.url + '&' + config.method, f: c }); }); return Promise.resolve(config) }, error => { return Promise.reject(error) }) // http響應攔截器 axios.interceptors.response.use(data => { removePending(data.config); //在一個axios響應後再執行一下取消操做,把已經完成的請求從pending中移除 return Promise.resolve(data) }, error => { //加載失敗 return {'data':{}} // return Promise.reject(error) })
通過屢次測試發現不一樣請求也給我取消了,緣由是沒有校驗請求參數,也就是說get請求能夠用,修改如下代碼數組
pending.push({ u: config.url + '&' + config.method, f: c });
修改成:函數
pending.push({ u: config.url + JSON.stringify(config.data) +'&' + config.method, f: c });//config.data爲請求參數
上面判斷也須要修改,這樣get請求和post均可以用了post
(我的理解)
官方提供了axios.CancelToken
來取消上一次請求方法,所以只須要判斷上一次請求是否重複。聲明數組變量 pending
用於存儲每一個請求實例的axios標識(請求方式,請求參數,請求url)和該實例的取消函數;在請求攔截器中建立取消函數實例,將請求的標識(判斷重複標識)及 該請求實例取消函數 push
到pending
數組中,建立取消上一次請求方法 removePending
,該方法主要判斷axios請求標識是否重複,重複則執行該實例的取消函數,而且從 pending
中移除標識及該實例取消函數。測試