个人笔记

在 apputil.js 文件中封装axios请求方法:

var cancelArr=[];
export { cancelArr }
export function axiosPostATM(params, transCode){
	let axiosTemp = axios.create({
		baseURL: process.env.API_ROOT_ATM,
		cancelToken : new axios.CancelToken(cancel => {
		    cancelArr.push({cancel})
		})
	});
	let finalUrl = 'TransServlet';//请求地址默认拼接TransServlet
	let finalData = getparams(params, transCode, 'service');//配置上行报文公共包头
	return new Promise(function(resolve, reject){
		axiosTemp.post(finalUrl, finalData).then(response => {
			let data = response.data;
			if(data.returnCode == successCode){
				resolve(data);
			}else{
				reject(data);
			}
		}).catch(error => {
			let err;
			if(error.message.indexOf('timeout') != -1){
				err = {
					returnMsg:'请求超时'
				};
			}else{
				err = {
					returnMsg:'通讯异常'
				};
			}
			reject(err);
		});
	});	
}

使用CancelToken来中断axios发起的请求,在 axios的配置中添加了如下代码:

cancelToken : new axios.CancelToken(cancel => {
   cancelArr.push({cancel})
})

在 main.js 文件中添加路由切换时中断axios请求方法:

import { cancelArr } from './common/publicJs/apputil.js'
router.beforeEach((to, from, next) => {
	cancelArr.forEach((ele,index)=>{
		ele.cancel()
		cancelArr.splice(index,1)
	})
	next()
})

这样就大功告成啦!

Logo

前往低代码交流专区

更多推荐