用户登录
用户注册

分享至

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

  • 作者: 娱小乐爱八卦
  • 来源: 51数据库
  • 2022-05-22

背景

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

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

效果如下:

分析

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

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

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

拦截请求和响应

方法不赘述。笔者在项目中使用 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 的 loading 方法。

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 一样。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

软件
前端设计
程序设计
Java相关