在某些特殊的場景業務下,需要手動停止未完成的Ajax請求,或在快速切換頁面時,停止上一頁面未完成的請求,減少資源浪費
實作目標:
- 封裝全域的變數及方法
- 通過全域方法的引入,在頁面直接呼叫該方法取消當前為完成的請求
- 無需引入,在使用vue的頁面可直接使用
實作方式
-
- 新建JS檔案,單獨封裝方法
- 在main.js中引入該JS檔案,進行全域注入 (或者直接在main.js中注入方法)
- 在單個請求中單獨添加cancelToken標識
- 全部請求(axios封裝位置)發起時添加cancelToken標識
- 呼叫全域方法停止當前正在進行的Ajax請求
1、在main.js中注入方法
/**
*取消正在進行中請求
* cancelList設定批量取消的介面,/**代表符合該規則的全部介面
* * 全域方法$cancelRequest可取消當前cancelList中的正在請求requset
* * 全域方法$cancelRequest("url")可控制取消單個請求
* */
const cancelDefaltList = ['/user/name','/org/number/**']
Vue.prototype.$currentHttpRequestList = new Map();
Vue.prototype.$cancelRequest = function(key) {
if (key) {
if (key.indexOf('/**') > -1) {
Vue.prototype.$currentHttpRequestList.forEach((item, key) => {
key.indexOf(key.split('/**')[0]) > -1 && item('Operation canceled by the user.');
});
} else {
Vue.prototype.$currentHttpRequestList.get(key) && Vue.prototype.$currentHttpRequestList.get(key)('Operation canceled by the user.');
}
} else {
cancelList.forEach(eachWite => {
Vue.prototype.$currentHttpRequestList.forEach((item, key) => {
key.indexOf(eachWite.split('/**')[0]) > -1 && item('Operation canceled by the user.')
})
})
}
};
2、 在在請求攔截器中添加(也可以按照需求在某些請求中單獨添加)cancelToken標識
axios.interceptors.request.use(
function(config) {
const CancelToken = axios.CancelToken;
var token = getToken();
config.headers['Content-Type'] = 'application/json; charset=UTF-8';
config.headers.Authorization = 'bearer ' + token; // 設定請求頭
//添加cancelToken標識
config.cancelToken = new CancelToken(function executor(c) {
Vue.prototype.$currentHttpRequestList.set(config.url, c);
});
return config;
},
function(err) {
if (err && err.message === 'Operation canceld by the user.') {
console.log(err, 'errorcancel');
return;
}
return Promise.reject(err);
}
);
3、按照需求(業務邏輯)呼叫全域方法停止當前正在進行的Ajax請求
<template>
</template>
<script>
export default {
name: 'test',
data() {
return {};
},
created(){
//實際使用位置需根據具體的業務場景需求而定,此處放在created中只是個示例
this.$cancelRequest('/user/name/**');//取消以‘/user/name/’開頭的正在進行中的請求
this.$cancelRequest('/user/age');//取消正在進行中的請求‘/user/age/’
this.$cancelRequest(); //取消cancelDefaltList設定的全部正在進行中的請求
},
methods: {}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/301064.html
標籤:其他
上一篇:DOM事件
