vue axios拦截器加全局loading

Posted on 2018-08-28 19:15  金-Fish  阅读(5445)  评论(1编辑  收藏  举报
import axios from 'axios'
import util from './util'
import {showFullScreenLoading, tryHideFullScreenLoading} from './axiosHelperLoading'

export default function () {
    axios.interceptors.request.use(
        req => {
            req.headers.token = localStorage.getItem('token') || '';
            showFullScreenLoading();
            return req
        },
        err => {
            return Promise.reject(err)
        }
    );
    axios.interceptors.response.use(
        res => {
            if (res.data.code === -2004) {
                // 登录失效,清楚token,刷新页面
                util.localStorage.remove('token');
                window.location.href = window.location.origin + "/#/login";
                return;
            }
            if (res.data.code === -2006) {
                window.location.href = window.location.origin + "/#/unauthorizedPage";
                return;
            }
            if (res.status !== 200 || res.data.code === '-1') {
                return Promise.reject(res)
            }
            tryHideFullScreenLoading();
            return res;
        },
        err => {
            return Promise.reject(err)
        }
    )
}

  loading下面

import {Loading} from 'element-ui';
import _ from 'lodash';
let needLoadingRequestCount = 0;
let loading;

function startLoading () {
    loading = Loading.service({
        lock: true,
        text: '加载中……',
        background: 'rgba(0, 0, 0, 0.7)'
    })
}

function endLoading() {
    loading.close()
}

const tryCloseLoading = () => {
    if (needLoadingRequestCount === 0) {
        endLoading();
    }
};

export function showFullScreenLoading () {
    if (needLoadingRequestCount === 0) {
        startLoading();
    }
    needLoadingRequestCount++;
}

export function tryHideFullScreenLoading () {
    if (needLoadingRequestCount <= 0) return;
    needLoadingRequestCount--;
    if (needLoadingRequestCount === 0) {
        _.debounce(tryCloseLoading, 300)()
    }
}