欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

vue+axios+element ui 实现全局loading加载示例

程序员文章站 2023-11-21 11:47:22
实现全局loading加载 分析需求,我们只需要在请求发起的时候开始loading,响应结束的时候关闭loading,就这么简单 对不对? import axi...

实现全局loading加载

分析需求,我们只需要在请求发起的时候开始loading,响应结束的时候关闭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)
 }
)

以上这篇vue+axios+element ui 实现全局loading加载示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。