使用elementUI和axios实现请求时添加loading遮罩层

需求
1.后台数据在800ms返回,不添加loading遮罩层
2.后台数据超过在800ms未返回,添加loading遮罩层

代码效果如下
请添加图片描述
前端代码

import axios from "axios";
import { Loading } from 'element-ui';

let loadingInstance = null;//蒙版实例
let timer = null;//定时器
// 创建axios实例
const instance = axios.create({ timeout: 1000 * 60 });
/**
 * 设置默认请求头
 */
instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
instance.defaults.headers.delete['Content-Type'] = 'application/x-www-form-urlencoded';
instance.defaults.headers.put['Content-Type'] = 'application/x-www-form-urlencoded';
//添加默认请求路径
if (process.env.NODE_ENV == 'development') {
  instance.defaults.baseURL = '/myapi';
}
else if (process.env.NODE_ENV == 'production') {
  instance.defaults.baseURL = "";
}
/** 
 * 请求拦截器 
 * 1. 每次请求前,添加蒙板
 */
instance.interceptors.request.use(
  config=> {
    // 添加遮罩层
    if (timer !== null) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      //如果存在则关闭
      if (loadingInstance !== null) {
        loadingInstance.close();
      }
      loadingInstance = Loading.service({
        lock: true,
        text: '努力加载中!',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      });
    }, 800);
    return config;
  },
  error=>Promise.error(error)
)
/** 
 * 响应拦截器
 * 
 */
 instance.interceptors.response.use(
  // 请求成功
  res => {
    //如果请求返回快的话,就不需要loading
    // 清除定时器
    clearTimeout(timer);
    timer = null;
    // 请求返回后,关闭loading
    if (loadingInstance !== null) {
      loadingInstance.close();
    }
    if (res.status === 200) {
      return Promise.resolve(res.data);
    } else {
      return Promise.reject(res.data);
    }
  },
  error=> {
    //如果请求返回快的话,就不需要loading
    // 清除定时器
    clearTimeout(timer);
    timer = null;
    // 请求返回后,关闭loading
    if (loadingInstance !== null) {
      loadingInstance.close();
    }
    return Promise.reject(error);
  }
 )
export default instance;

后台代码

/* GET users listing. */
router.get('/getName1', function(req, res, next) {
  res.json({
    name: "喝鸡汤"
  });
});

router.get('/getName2', function(req, res, next) {
  setTimeout(()=> {
    res.json({
      name: "穿山甲"
    });
  },3000);
});
router.get('/getName3', function(req, res, next) {
  res.json({
    name: "你先喝"
  });
});

嗯嗯,就这样咯,有问题请指正;
觉得有用就给个赞吧

  • 2
    点赞
  • 3
    收藏
  • 打赏
    打赏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

博客写好-开发CV

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值