更改路由使用vue-router时中止所有Axios请求 [英] abort all Axios requests when change route use vue-router
问题描述
当我更改路线使用方式时,如何在完成之前中止/取消Axios请求 Vue路由器.
how can i abort / cancel Axios request before complete when i change route use vue-router.
当用户打开页面时,它会自动发送axios请求以获取一些数据, 但是用户不等待获取响应,则他正在通过vue-router更改路由 将会有很多Axios请求
when user open page it automatically send axios request to get some data, but user don't waiting to get response then he is changing route by vue-router it will be a lot of Axios requests
所以我的问题有解决办法吗
so is there any solve to my problem
推荐答案
基本上,您必须生成一个全局取消令牌
Basically you have to generate a global cancel token
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
并通过在config参数中传递它在所有请求中使用
and use it in all your requests by passing it in the config parameter
获取请求:
axios.get('/user/12345', {
cancelToken: source.token
}).catch(function(thrown) {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
// handle error
}
});
POST请求:
axios.post('/user/12345', {
name: 'new name'
}, {
cancelToken: source.token
})
然后,在vue-router beforeEach
导航防护中,您可以使用以下命令取消所有请求:
Then, within a vue-router beforeEach
navigation guard you can cancel all requests using:
source.cancel('Operation canceled by the user.');
这是官方的axios取消指南: https://github.com/axios/axios#cancellation
Here's the official axios guide for cancellation: https://github.com/axios/axios#cancellation
这篇关于更改路由使用vue-router时中止所有Axios请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!