Update: Axios (0.22.0+)
CancelToken
is now deprecated. Check @m0r answer for updated solution using AbortController
. Here is the link from the official documentation:
https://axios-http.com/docs/cancellation
Original answer
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 request:
axios.get('/user/12345', {
cancelToken: source.token
}).catch(function(thrown) {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
// handle error
}
});
POST request:
axios.post('/user/12345', {
name: 'new name'
}, {
cancelToken: source.token
})
Then, within a vue-router beforeEach
navigation guard you can cancel all requests using:
source.cancel('Operation canceled by the user.');
Here's the official axios guide for cancellation: https://github.com/axios/axios#cancellation