1.axios方案
在axios请求里面统一添加loading
先申明两个变量,记录页面是否有loading和请求个数
let loadingInstance,//记录页面中存在的loading loadingCount = 0 //记录当前正在请求的数量
在请求开始的时候判断页面是不是有loading,如果没有loading,就创建一个loading
响应的时候,关闭loading
错误的时候,关闭loading
这样一来,就会有一个问题,页面中有多个请求正在进行的时候,前面的请求提前收到响应,后面的loading就不会出来
上面这个图 loading 可能只会存在10s,其实应该是15s
解决办法:
用一个变量记录页面的正在进行的请求数,并进行呢维护这个值,如果新来一个请求就加1,结束就减去1,错误的也减去1
在loading要进行关闭的时候判断
只有这个值为0的时候才去关闭loading
代码:
let loadingInstance,loadingCount = 0 //申明loading //http request 拦截器 axios.interceptors.request.use( config => { console.log("打开前"+loadingCount) if (loadingCount == 0) { console.log("有loading了") console.log("打开时"+loadingCount) loadingInstance = Loading.service({ lock: true, customClass: "z-index999", text: "数据加载中,请稍后...", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)" }) } loadingCount++ let Authorization = cookies.get('access_token') ? { "Authorization": "Bearer " + cookies.get('access_token') } : {} let headers = { "language": "zh_cn", "Content-Type": "application/x-www-form-urlencoded" } config.headers = Object.assign(Authorization, headers) return config }, error => { // loadingCount-- // if (loadingInstance && loadingCount==0) { // loadingInstance.close() // } return Promise.reject(err); } ); //响应拦截器即异常处理 axios.interceptors.response.use(response => { loadingCount-- console.log("关闭时的"+loadingCount) if (loadingInstance && loadingCount == 0) { loadingInstance.close() } //console.log(response) switch (response.status) { case 200: responseBefore(response) return response break case 400: return Promise.resolve({ code: response.status, message: '错误请求' }) break case 401: return Promise.resolve({ code: response.status, message: '未授权,请重新登录' }) break default: return Promise.resolve({ status: response.status, message: '未知错误' }) break } }, error => { // loadingCount-- // if (loadingInstance && loadingCount == 0) { // loadingInstance.close() // } console.warn(`timeout of ${axios_defaults_timeout}ms exceeded`); return Promise.reject(error) })
将loading继续进行封装(带参数)
import { Loading } from 'element-ui' let loadingCount = 0 let loading const startLoading = (options = {}) => { loading = Loading.service({ lock: true, text: '加载中……', background: 'rgba(0, 0, 0, 0.7)', ...options, }) } const endLoading = () => { loading.close() } export const showLoading = (options) => { if (loadingCount === 0) { startLoading(options) } loadingCount += 1 } export const hideLoading = () => { if (loadingCount <= 0) { return } loadingCount -= 1 if (loadingCount === 0) { endLoading() } } export default function(Vue) { //添加全局API Vue.prototype.$loading = { showLoading, hideLoading } }
main.js引入;
import loading from '@frameworks/assets/js/Loading'
注意一定要use
Vue.use(loading)
最后一步就是调用了
this.$loading.showLoading()//打开 this.$loading.hideLoading()//关闭