项目需求:用自定义的 .gif 图标实现全局 loading 效果;为避免在每个页面手动添加,且简单高效的实现,经查阅资料,最终采用了 vue axios拦截器 + 自编写 loading 插件;下面直接贴上代码~

在公用模块定义loading文件,含 index.js,loading.vue文件,文件结构如下:

注:loading.vue 与 index.js 之间的传值通过props实现,代码如下:

loading.vue

<template>
  <div class="load-model" v-show="showLoading">
    <img src="../images/loading.gif" alt="loading...">
  </div>
</template>

<script>
export default {
  data(){
    return {

    }
  },
  props:{
    showLoading:false
  }
}
</script>

<style scoped>
.load-model{
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  /*background:rgba(255,255,255,0.8);*/
   /* background:rgba(0,0,0,0.6); */
}
.load-model > img{
  width: 12rem;
  height: 12rem;
  margin-top: -5rem;
}
</style>

index.js

let loadTemp = require('./loading.vue').default; // cli3.0以后引入vue模板需要default

let Load = {}; // 定义插件对象
Load.install = (Vue,options) => { // Vue的install方法,用于定义vue插件
  // 如果存在loading 不重复创建DOM
  if(document.getElementsByClassName('.load-model').length) return;

  let lTemp = Vue.extend(loadTemp);

  // 实例化VUE实例
  let $vm = new lTemp();

  // 此处使用$mount来手动开启编译,用$el来访问元素,并插入到body中
  let tpl = $vm.$mount().$el;
  document.body.appendChild(tpl);

  Vue.prototype.$loading = { // 在Vue的原型上添加实例方法,以全局调用
    show(options){
      if(options == "loading"){
        $vm.showLoading = true;
      }
    },
    hide(){
      $vm.showLoading = false;
    }
  }
}

// 导出Load
export default Load;

插件写完后在main.js 中全局调用:

import Loading from './common/loading'

Vue.use(Loading)

这样的话我们就可以在所需要调用的页面调用如下方法:

this.$loading.show("loading"); // 触发 loading 事件
this.$loading.hide(); // 关闭 loading 事件

这样的添加只适用于项目小然后页面比较少的情况下,在大项目下或页面较多的情况下,这样维护起来很繁琐且麻烦,由此我们借用 axios 拦截器,保证统一在一个地方触发与关闭,如下为 axios 拦截器的代码:

开启 loading 效果的代码为:Vue.prototype.$loading.show("loading");

关闭 loading 效果的代码为:Vue.prototype.$loading.hide();

axios_api.js

import Vue from 'vue';
import axios from 'axios';//更改http请求插件
import {Indicator, Toast} from 'mint-ui';

let toast = function (text) {
  Toast({
    message: text,
    duration: 2000
  })
};

// 设置全局的请求次数,请求的间隙
axios.defaults.retry = 1;
axios.defaults.retryDelay = 500;

axios.interceptors.request.use(config => {
  Vue.prototype.$loading.show("loading");
  config.timeout = 60000;
  config.headers['Content-Type'] = 'application/json;charset=utf-8';
  return config
}, error => {
  return Promise.reject(error)
});
axios.interceptors.response.use(response => {
  if (response.status == 200) {
    setTimeout(() => {
      Vue.prototype.$loading.hide();
    },500);
  } else {
    setTimeout(() => {
      Vue.prototype.$loading.hide();
    },500);
    toast('获取数据失败');
  }
  return response;
}, error => {
  // var config = error.config;
  // if (!config || !config.retry) return Promise.reject(error);
  // config.__retryCount = config.__retryCount || 0;
  // if (config.__retryCount >= config.retry) {
  setTimeout(() => {
    Vue.prototype.$loading.hide();
  },500);
  if (error.response) {
    switch (error.response.status) {
      case 0:
        toast('网络连接超时');
        break;
      case 404:
        toast('您请求的功能不存在');
        break;
      case 408:
        toast('请求超时');
        break;
      default:
        toast('请求失败');
        break;
    }
    return Promise.reject(error.response.data);
  } else {
    if (!axios.isCancel(error)) {
      toast('网络连接超时');
    }
    return Promise.reject(error);
  }
  // }
  // config.__retryCount += 1;
  // var backoff = new Promise(function (resolve) {
  //   setTimeout(function () {
  //     resolve();
  //   }, config.retryDelay || 1);
  // });
  // return backoff.then(function () {
  //   return axios(config);
  // });
});

export default axios;

vue axios拦截器 + 自编写插件 实现全局 loading 效果;的更多相关文章

  1. vue --- axios拦截器+form格式请求体

    在vue2.x中使用CLI生成的模板有很大改变,需要自己手动在main.ts同级目录下新建interceptors.ts interceptors.ts import axios from 'axio ...

  2. vue axios 拦截器

    前言 项目中需要验证登录用户身份是否过期,是否有权限进行操作,所以需要根据后台返回不同的状态码进行判断. 第一次使用拦截器,文章中如有不对的地方还请各位大佬帮忙指正谢谢. 正文 axios的拦截器分为 ...

  3. vue axios拦截器的封装

    // request.js import axios from 'axios' import qs from 'qs' // 创建axios实例 const service = axios.creat ...

  4. vue axios拦截器介绍

    关于axios的拦截器是一个作用非常大,非常好用的东西.分为请求拦截器和响应拦截器两种.我一般把拦截器写在main.js里. 1. 请求拦截器 请求拦截器的作用是在请求发送前进行一些操作,例如在每个请 ...

  5. vue axios拦截器加全局loading

    import axios from 'axios' import util from './util' import {showFullScreenLoading, tryHideFullScreen ...

  6. Vue基于vuex、axios拦截器实现loading效果及axios的安装配置

    准备 利用vue-cli脚手架创建项目 进入项目安装vuex.axios(npm install vuex,npm install axios) axios配置 项目中安装axios模块(npm in ...

  7. vue导航守卫和axios拦截器的区别

    在Vue项目中,有两种用户登录状态判断并处理的情况,分别为:导航守卫和axios拦截器. 一.什么是导航守卫? vue-router 提供的导航守卫主要用来通过跳转或取消的方式守卫导航.(在路由跳转时 ...

  8. Vue2学习小记-给Vue2路由导航钩子和axios拦截器做个封装

    1.写在前面 最近在学习Vue2,遇到有些页面请求数据需要用户登录权限.服务器响应不符预期的问题,但是总不能每个页面都做单独处理吧,于是想到axios提供了拦截器这个好东西,再于是就出现了本文. 2. ...

  9. 12. 前后端联调 + ( proxy代理 ) + ( axios拦截器 ) + ( css Modules模块化方案 ) + ( css-loader ) + ( 非路由组件如何使用history ) + ( bodyParser,cookieParser中间件 ) + ( utility MD5加密库 ) + ( nodemon自动重启node ) + +

    (1) proxy 前端的端口在:localhost:3000后端的端口在:localhost:1234所以要在webpack中配置proxy选项 (proxy是代理的意思) 在package.jso ...

随机推荐

  1. SNF快速开发平台项目实践介绍

    SNF快速开发平台分如下子平台: 1.CS快速开发平台 2.BS快速开发平台 3.H5移动端快速开发平台 4.软件开发机器人平台(目前是CS版本,后续有规划BS版本) SNF快速开发平台是一个比较成熟 ...

  2. 【谷歌浏览器】【谷歌地球】【Adobe 软件】离线安装包的下载地址

    因为某些原因?我们需要下载谷歌浏览器的离线安装版,找了好几次地址了,这次自己记录一下吧! 主要就是加两个参数,standalone 就是离线安装吧,platform 就是平台版本吧,哈~ 离线32位: ...

  3. HMACSHA1 加密算法

    https://blog.csdn.net/z69183787/article/details/78393216 ******************************************* ...

  4. 【iCore4 双核心板_ARM】例程二十九:SD_IAP_FPGA实验——更新升级FPGA

    实验现象及操作说明: 1.烧写程序成功,绿色ARM·LED灯点亮,三色FPGA·LED灯循环点亮,烧写失败,如果挂载SD卡失败,红灯快闪,如果打开文件失败,蓝灯快闪,读取文件指针移动失败,白灯点亮,升 ...

  5. MA5680T OLT管理软件,全智能判断板卡,无人值守策略,根据光猫类型自动扫描添加光猫

    轻量型的ONU查询工具,智能查询板卡,查询自动发现,搜索ONU等功能,需要更多智能功能,可联系QQ:561454825 下载地址:下载地址1

  6. elephant-bird学习笔记

    elephant-bird是Twitter的开源项目,项目的地址为 https://github.com/twitter/elephant-bird 该项目是Twitter为LZO,thrift,pr ...

  7. ajax方法如何给全局变量赋值

    在调用一个jquery的ajax方法时我们有时会需要该方法返回一个值或者给某个全局变量赋值,可是我们发现程序执行完后并没有获取到我们想要的值,这时很有可能是因为你用的是ajax的异步调用async:t ...

  8. C# 服务端篇之实现RestFul Service开发(简单实用)

    一.RestFul简介 REST(Representational State Transfer 通常被翻译为“表述性状态传输”或者“表述性状态转移”)是RoyFielding提出的一个描述互联系统架 ...

  9. 使用AS-REP Roasting和kerberoasting攻击kerberos

    准备工作 ''' PowerView是PowerSploit框架的一个子集,里面继承了很多和渗透相关的powershell脚本下载地址:https://github.com/PowerShellMaf ...

  10. 关于vmware 11.1安装windows 7操作系统时报错 Unist specified don’t exist. SHSUCDX can’t install

    笔者今天在vmware 11.1 虚拟机下使用光驱安装windows 7 32位操作系统时,报错: Unist specified don’t exist. SHSUCDX can’t install ...