1.为设么要使用全局loading
调用的每一个接口都要绑定一个loading真的很烦。
2.实现这个需要考虑哪些要素
- 首先全局的loading需要一个调用任何接口都要执行的地方打开,那就肯定是axios的前置拦截函数了。
- loading有加载整个页面的,也有加载部分页面的(下拉框内容展示区等),所以不是所有接口都能使用全局loading,这就需要使用一个白名单,只对白名单内存在的接口进行处理
- 关闭loading,那就肯定是axios的后置拦截函数了。
- 当同时请求多个接口,如何判断所有接口请求完成后关闭loading。用一个数组存储请求的接口路径,axios后置拦截函数中删除数组中返回状态的接口,数组长度=0,关闭loading即可。
3.实现
let apiList = []; // 存储请求的接口
api.interceptors.request.use(request => {let {interfaceLoading,whiteList} = store.state.global// 启动全局lodingif(whiteList.indexOf(request.url) > -1 && !interfaceLoading){store.commit('global/setInterfaceLoading',true)// 记录请求接口,用于判断何时取消loadingapiList.push(request.url)}return request}
)api.interceptors.response.use(response => {// 清除请求地址,清空则取消loadinglet index = apiList.findIndex((item)=>item===response.config.url)if(index!==-1){apiList.splice(index,1)}if(apiList.length===0){store.commit('global/setInterfaceLoading',false)}// 以下为处理返回数据结果if (response.data) {if (response.data.status === 200) {return Promise.resolve(response.data)}else if (response.data.errorType) {// alert.typeOne('error',response.data.msg)return Promise.resolve(response.data)} else {// 请求成功并且没有报错return Promise.resolve(response.data)}} else {toLogin()}}
)