vue+axios+element ui实现全局配置loading.

版权声明:本文原创为夏狮狮,转载请说明出处! https://blog.csdn.net/weixin_42470791/article/details/85085493

背景
业务需求是这样子的,每当发请求到后端时就触发一个全屏的 loading,多个请求合并为一次 loading。
现在项目中用的是 vue 、axios、element等,所以文章主要是讲如果使用 axios 和 element 实现这个功能。

效果如下:
在这里插入图片描述

要点分析=重点
首先,请求开始的时候开始 loading, 然后在请求返回后结束 loading。重点就是要拦截请求和响应。
然后,要解决多个请求合并为一次 loading。
最后,调用element 的 loading 组件即可。

代码块

import axios from 'axios';
import { Message, Loading } from 'element-ui';
import Cookies from 'js-cookie';
import router from '@/router/index'
let loading        //定义loading变量
function startLoading() {    //使用Element loading-start 方法
    loading = Loading.service({
        lock: true,
        text: '加载中……',
        background: 'rgba(0, 0, 0, 0.7)'
    })
}
function endLoading() {    //使用Element loading-close 方法
    loading.close()
}
//那么 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()
    }
}

//http request 拦截器
axios.interceptors.request.use(
    config => {
        var token = ''
        if(typeof Cookies.get('user') === 'undefined'){
            //此时为空
        }else {
            token = JSON.parse(Cookies.get('user')).token
        }//注意使用的时候需要引入cookie方法,推荐js-cookie
        config.data = JSON.stringify(config.data);
        config.headers = {
            'Content-Type':'application/json'
        }
        if(token != ''){
          config.headers.token = token;
        }
        showFullScreenLoading()
        return config;
    },
    error => {
        return Promise.reject(err);
    }
);
//http response 拦截器
axios.interceptors.response.use(
    response => {
        //当返回信息为未登录或者登录失效的时候重定向为登录页面
        if(response.data.code == 'W_100004' || response.data.message == '用户未登录或登录超时,请登录!'){
            router.push({
                path:"/",
                querry:{redirect:router.currentRoute.fullPath}//从哪个页面跳转
            })
        }
        tryHideFullScreenLoading()
        return response;
    },
    error => {
        return Promise.reject(error)
    }
)

猜你喜欢

转载自blog.csdn.net/weixin_42470791/article/details/85085493
今日推荐