温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2021-05-21 10:31:23 来源:亿速云 阅读:300 作者:小新 栏目:web开发

这篇文章将为大家详细讲解有关vue+axios+element ui如何实现全局loading加载示例,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

实现全局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

Vue是一款友好的、多用途且高性能的JavaScript框架,使用vue可以创建可维护性和可测试性更强的代码库,Vue允许可以将一个网页分割成可复用的组件,每个组件都包含属于自己的HTML、CSS、JavaScript,以用来渲染网页中相应的地方,所以越来越多的前端开发者使用vue。

关于“vue+axios+element ui如何实现全局loading加载示例”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI