scenario

When the routing page is switched, the request on the previous page should be terminated, and new request should be added to the network after the actual route is switched.

The request for the previous page will remain pending until the request is successfully loaded or times out.

Train of thought

Use axios interceptors and cancelToken

The request is placed in an array of global variables in the AXIos interceptor wrapped JS, which can be hung on the Window object or managed using vuex, and all requests in the array are eliminated in the route global front-guard

The solution

  1. Request Request interceptor
Window. AxiosPromiseArr = [] / / axios set in place to cancel object axios. Interceptors. Request. Use (config = > {/ / save the page by requests all requests config.cancelToken = new axios.CancelToken(cancel => { window.axiosPromiseArr.push({ cancel }) }); return config });Copy the code
  1. Response Response interception
Axios. Interceptors. Response. Use (res = > {/ / event handling}, the error = > {the if (axios. IsCancel (error)) {/ / in order to put an end to the chain of promise Return new Promise(() =>{}); return new Promise(() =>{}); }else{ return Promise.reject(error) } });Copy the code
  1. Unsave axiosPromiseArr when entering route hook interception
Route.beforeeach ((to, from, next) => {window._axiospromisear.foreach ((ele,index) => {ele.cancel() // Before routing forward, // Empty the request parameter delete window._axiosPromiseArr[index]}); });Copy the code