vue+elementUI+axios实现的全局loading加载动画(部分接口不要loading)

loading.js文件封装loading
import { Loading } from 'element-ui'

let loading
function startLoading () {
  loading = Loading.service({
    lock: true,
    text: '加载中',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.2)'
  })
}

function endLoading () {
  loading.close()
}

//那么 showFullScreenLoading() tryHideFullScreenLoading() 就是将同一时刻的请求合并。
//声明一个变量 needLoadingRequestCount,每次调用showFullScreenLoading方法 needLoadingRequestCount + 1。
//调用tryHideFullScreenLoading()方法,needLoadingRequestCount - 1。needLoadingRequestCount为 0 时,结束 loading。
let needLoadingRequestCount = 0
const showFullScreenLoading = function() {
  if (needLoadingRequestCount === 0) {
    startLoading()
  }
  needLoadingRequestCount++
}

const tryHideFullScreenLoading = function() {
  if (needLoadingRequestCount <= 0) return
  needLoadingRequestCount--
  if (needLoadingRequestCount === 0) {
    endLoading()
  }
}

export {
  startLoading,
  endLoading,
  showFullScreenLoading,
  tryHideFullScreenLoading
}
http.js文件封装请求
// 引入axios以及element ui中的loading和message组件
import axios from 'axios'
import router from '../router/index'
import { Message } from 'element-ui'
import { showFullScreenLoading,  tryHideFullScreenLoading } from '@/utils/loading'

// http请求拦截器
axios.interceptors.request.use(
  config => {
    if (config.headers.isLoading !== false) {
      // 如果配置了isLoading: false,则不显示loading
      showFullScreenLoading()
    }
    config.headers['UserId'] = localStorage.getItem('username')
    config.headers['Brand'] = localStorage.getItem('brand')
    config.headers['Authorization'] = localStorage.getItem('token')
    return config
  },
  error => {
    tryHideFullScreenLoading()
    Message.error({
      message: '加载超时'
    })
    return Promise.reject(error)
  }
)
// http响应拦截器
axios.interceptors.response.use(
  data => {
    // 响应成功关闭loading
    tryHideFullScreenLoading()
    return data
  },
  error => {
    //当返回信息为未登录或者登录失效的时候重定向为登录页面
    if (error.response.status == '401') {
      Message.error({
        message: error.response.data.msg
      })
      localStorage.clear()
      router.push({
        path: '/login',
        query: { redirect: router.currentRoute.fullPath } //从哪个页面跳转
      })
    }
    tryHideFullScreenLoading()
    return Promise.reject(error)
  }
)

export { axios }

axios设置请求头loading信息

(1)get请求

axios
  .get(url, {
    headers: {
      isLoading: false
    },
    params: {
      param1: string,
      param2: string
    }
  })
  .then(res => fn)
  .catch(e => fn)

(2)post请求

axios
  .post(
    urlString,
    {
      data: data
    },
    {
      headers: {
        isLoading: false
      }
    }
  )
  .then(res => fn)
  .catch(e => fn)

你可能感兴趣的:(axios,vue)