用Axios Element实现全局的请求loading的方法

业务需求是这样子的,每当发请求到后端时就触发一个全屏的 loading,多个请求合并为一次 loading。

现在项目中用的是 vue 、axios、element等,所以文章主要是讲如果使用 axios 和 element 实现这个功能。

效果如下:

用Axios Element实现全局的请求loading的方法

分析

首先,请求开始的时候开始 loading, 然后在请求返回后结束 loading。重点就是要拦截请求和响应。

然后,要解决多个请求合并为一次 loading。

最后,调用element 的 loading 组件即可。

拦截请求和响应

axios 的基本使用方法不赘述。笔者在项目中使用 axios 是以创建实例的方式。

// 创建axios实例 const $ = axios.create({ baseURL: `${URL_PREFIX}`, timeout: 15000 })

然后再封装 post 请求(以 post 为例)

export default { post: (url, data, config = { showLoading: true }) => $.post(url, data, config) }

axios 提供了请求拦截和响应拦截的接口,每次请求都会调用showFullScreenLoading方法,每次响应都会调用tryHideFullScreenLoading()方法

// 请求拦截器 $.interceptors.request.use((config) => { showFullScreenLoading() return config }, (error) => { return Promise.reject(error) }) // 响应拦截器 $.interceptors.response.use((response) => { tryHideFullScreenLoading() return response }, (error) => { return Promise.reject(error) })

那么showFullScreenLoading tryHideFullScreenLoading()要干的事儿就是将同一时刻的请求合并。声明一个变量needLoadingRequestCount,每次调用showFullScreenLoading方法 needLoadingRequestCount + 1。调用tryHideFullScreenLoading()方法,needLoadingRequestCount - 1。needLoadingRequestCount为 0 时,结束 loading。

let needLoadingRequestCount = 0 export function showFullScreenLoading() { if (needLoadingRequestCount === 0) { startLoading() } needLoadingRequestCount++ } export function tryHideFullScreenLoading() { if (needLoadingRequestCount <= 0) return needLoadingRequestCount-- if (needLoadingRequestCount === 0) { endLoading() } }

startLoading()和endLoading()就是调用 element 的 。

import { Loading } from 'element-ui' let loading function startLoading() { loading = Loading.service({ lock: true, text: '加载中……', background: 'rgba(0, 0, 0, 0.7)' }) } function endLoading() { loading.close() }

到这里,基本功能已经实现了。每发一个 post 请求,都会显示全屏 loading。同一时刻的多个请求合并为一次 loading,在所有响应都返回后,结束 loading。

功能增强

实际上,现在的功能还差一点。如果某个请求不需要 loading 呢,那么发请求的时候加个  showLoading: false的参数就好了。在请求拦截和响应拦截时判断下该请求是否需要loading,需要 loading 再去调用showFullScreenLoading()方法即可。

在封装 post 请求时,已经在第三个参数加了 config 对象。config 里包含了 showloading。然后在拦截器中分别处理。

// 请求拦截器 $.interceptors.request.use((config) => { if (config.showLoading) { showFullScreenLoading() } return config }) // 响应拦截器 $.interceptors.response.use((response) => { if (response.config.showLoading) { tryHideFullScreenLoading() } return response })

我们在调用 axios 时把 config 放在第三个参数中,axios 会直接把 showloading 放在请求拦截器的回调参数里,可以直接使用。在响应拦截器中的回调参数 response 中则是有一个 config 的 key。这个 config 则是和请求拦截器的回调参数 config 一样。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/pxsdj.html