更改路由时中止所有 Axios 请求使用 vue-router [英] 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();
并通过在配置参数中传递它来在所有请求中使用它
and use it in all your requests by passing it in the config parameter
GET 请求:
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
这篇关于更改路由时中止所有 Axios 请求使用 vue-router的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!