vue+elementUI+axios实现的全局loading加载动画

时间:2023-03-09 06:34:26
vue+elementUI+axios实现的全局loading加载动画

在项目中,很多时候都需要loading加载动画来缓解用户的焦虑等待,比如说,我打开了一个页面,而这个页面有很多接口请求,但浏览器的请求并发数就那么几个,再加上如果网速不行的话,那么这时候,用户很可能就会纠结自己到底该不该留下来继续等待呢。

所以,这时候,loading动画就是一种缓解等待情绪的方式,当然还有更高端的,比如:骨架屏。有兴趣的朋友可以自行研究,我后续也会找机会分享一下。

下面,开始本文的主要内容,目前我在用的是Vue 2.x版本,ajax请求用的是axios,UI框架用的是elementUI。所以下面的loading用的是UI框架中的组件。

唠叨了这么多,接下来分享一下具体实现的代码(里面很多代码逻辑我已经去掉了,只剩下基础的部分):

代码可放在main.js中。

import Vue from 'vue'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import axios from 'axios' // loading框设置局部刷新,且所有请求完成后关闭loading框
let loading
let needLoadingRequestCount = 0 // 声明一个对象用于存储请求个数
function startLoading () {
loading = Vue.prototype.$loading({
lock: true,
text: '努力加载中...',
background: 'rgba(0,0,0,0.5)',
target: document.querySelector('.loading-area') // 设置加载动画区域
})
}
function endLoading () {
loading.close()
}
function showFullScreenLoading () {
if (needLoadingRequestCount === 0) {
startLoading()
}
needLoadingRequestCount++
}
function hideFullScreenLoading () {
if (needLoadingRequestCount <= 0) return
needLoadingRequestCount--
if (needLoadingRequestCount === 0) {
endLoading()
}
} // axios
axios.defaults.baseURL = process.env.NODE_ENV === 'production' ? '' : '/api' // 接口基础路径
axios.defaults.timeout = 20000 // 超时时间 20s
// axios.defaults.withCredentials = true // 允许设置cookie(开启的话需后端配置)
// http请求拦截器
axios.interceptors.request.use(config => {
if (config.isLoading !== false) { // 如果配置了isLoading: false,则不显示loading
showFullScreenLoading()
}
config.headers['Content-Type'] = 'application/json;charset=UTF-8'
return config
}, error => {
hideFullScreenLoading()
return Promise.reject(error.response)
})
// http响应拦截器
axios.interceptors.response.use(data => {
hideFullScreenLoading() // 响应成功关闭loading
return data
}, error => {
hideFullScreenLoading()
let _status = error.response && error.response.status
if (_status === 504 || _status === 404) {
// 跳转404页面(目前没有,只能先跳转首页)
//router.push({ path: '/' })
}
return Promise.reject(error)
})
Vue.prototype.$http = axios

  ok,上面的代码就实现了全屏的loading动画。
注意:loading的样式是可以自定义的,文案也是可以自定义的。