demand

Loading begins when the request begins and ends when the request returns.

The point is to intercept requests and responses.

Then, to solve the problem of sending multiple requests in parallel in a short period of time, merge it into a single loading.

Git address github.com/caozhenhui/…

Import axios from 'axios' const $axios = axios.create({baseURL: '/ API ', timeout: // Axios provides an interface for request interception and response interception. The startLoading method is called on each request. Each response calls the endLoading method // startLoading. All endLoading does is combine requests at the same time. Declare a variable reqNum and call the startLoading method reqNum + 1 each time. Call the endLoading() method, reqnum-1. When reqNum is 0, End loading let reqNum = 0 function startLoading () {if (reqNum === 0) {console.log(' started loading')} reqNum++} function EndLoading () {setTimeout(closeLoading) {setTimeout(closeLoading); 300) closeLoading() } function closeLoading () { if (reqNum <= 0) return reqNum-- if (reqNum === 0) { The console. The log (' end loading ')}} / / request interceptor $axios. Interceptors. Request. Use (config = > {/ / if a request doesn't need to loading? ShowLoading: false is a good parameter to send the request. Determine whether the request needs to be loaded during request interception and response interception. // Config. Headers [' token '] = startLoading() return config} (error) = > {return Promise. Reject (error)}) / / response interceptor $axios. Interceptors. Response. Use (response = > {endLoading () return Response}, (error) => {// public error error // if (error.response) {// switch (error.response.status) {// case 404: // console.log(' page not found '); Break // case 500: // console.log(' server error '); Break // default: break //} //} // endLoading endLoading() return promise.reject (error)}) export default {post: (url, data, headers) => $axios.post(url, data, { headers }), get: Let t = new Date().gettime () data.t = t return $axios.get(url, {params: data, headers }) } }Copy the code