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

使用elementui的loading

程序员文章站 2022-03-04 11:34:05
...

首先写一个loading.js文件

import { Loading } from 'element-ui';

let loadingCount = 0;
let loading;

const startLoading = () => {
  loading = Loading.service({
    lock: true,
    text: '加载中……',
    background: 'rgba(0, 0, 0, 0.7)'
  });
};

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();
  }
};

然后添加全局拦截

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

/* 请求拦截器(请求之前的操作) */
ajax.interceptors.request.use((req) => {
  showLoading();
  return req;
}, err => Promise.reject(err));

/* 请求之后的操作 */
ajax.interceptors.response.use((res) => {
  hideLoading();

  return res;

  return Promise.reject(res);
}, (err) => {
  hideLoading();
  return Promise.reject(err);
});