Element UI 请求拦截器(异步请求时显示请求中..)

前端页面为了更加迎合用户的需求,带来很好的用户体验。但有的时候,获取数据量太大的话,页面没有任何提示,用户体验不是很好。所以这里我用到这个Element UI其中的模块,完善了一下用户交互效果。

首先,创建一个 Loading.js 文件用来存储 Element UILoading 配置.

代码如下:

import { Loading } from 'element-ui';
 
let loadingCount = 0;
let loading;
 
const startLoading = () => {
  loading = Loading.service({
    lock: true,
    text: '加载中……',
    background: 'rgba(255, 255, 255, 0.7)',
    target: document.querySelector('#table')
  });
};
 
const endLoading = () => {
  loading.close();
};

export const showLoading = () => {
  if (loadingCount === 0) {
    startLoading();
  }
  loadingCount += 1;
};
 
export const hideLoading = () => {
  if (loadingCount <= 0) {
    return;
  }
  loadingCount -= 1;
  if (loadingCount === 0) {
    endLoading();
  }
};

配置完成之后,找到 Axios 请求的配置文件添加以下代码,用于发送 Axios 即可调用 Loading 方法

import axios from 'axios'
import { showLoading, hideLoading } from './loading';

const service = axios.create({
  baseURL: Ip地址+端口号
  // 所有方法的超时时间都设置为2秒
  timeout: 2000 // request timeout
})

// 拦截器拦截axios请求显示加载页面
service.interceptors.request.use((req) => {
  if (req.url.indexOf('/bim-yasha/') == -1) {
    showLoading();
  }
  return req;
}, err => Promise.reject(err));
 
/* 请求之后的操作 */
service.interceptors.response.use((res) => {
  if (res.config.url.indexOf('/bim-yasha/') == -1) {
    hideLoading();
  }
  return res;
}, (err) => {
  hideLoading();
  return Promise.reject(err);
});

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值