【Vue】基于ElementUI的全局Loading

11/16/2021 Vue开发技巧

# 基于ElementUI的全局Loading

ElementUI + axios 实现的全局loading:

//  loading.js
import { Loading } from "element-ui";
import _ from 'lodash';

let loading = null;
let needRequestCount = 0;


//开启loading状态
const startLoading = (headers={}) => {
  loading = Loading.service({
    lock: true,
    text: headers.text||"加载中……",
    background: "rgba(0, 0, 0, 0.7)",
    target:headers.target||"body"
  });
};

//关闭loading状态
const endLoading = _.debounce(() => {
  loading.close();
  loading = null;
},300);


export const showScreenLoading=(headers)=>{
   if(needRequestCount == 0&&!loading){
    startLoading(headers);
   }
   needRequestCount++;
}

export const hideScreenLoading=()=>{
    if(needRequestCount<=0)  return 
    needRequestCount--;
    needRequestCount = Math.max(needRequestCount, 0);
    if(needRequestCount===0){
        endLoading()
    }
}
export default {};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// request.js
import axios from "axios";
import Lockr from "lockr";
import { showScreenLoading, hideScreenLoading } from "./loading";
import { Message } from "element-ui";

class Service {
  construct() {
    this.baseURL = process.env.VUE_APP_URL;
    this.timeout = 3000; //请求时间
  }
  request(config) {
    let instance = axios.create({
      baseURL: this.baseURL,
      timeout: this.timeout
    });
    //请求拦截器
    instance.interceptors.request.use(
      config => {
        config.headers.Authorization = Lockr.get("token");
        if (config.headers.showLoading !== false) {
          showScreenLoading(config.headers);
        }
        return config;
      },
      error => {
        if (config.headers.showLoading !== false) {
          hideScreenLoading(config.headers);
        }
        Message.error("请求超时!");
        return Promise.reject(error);
      }
    );
    //响应拦截器
    instance.interceptors.response.use(
      response => {
        if (response.status == 200) {
          setTimeout(() => {
            if (response.config.headers.showLoading !== false) {
              hideScreenLoading();
            }
          }, 500);
          return response.data;
        }
      },
      error => {
        if (response.config.headers.showLoading !== false) {
          hideScreenLoading();
        }
        return Promise.reject(error);
      }
    );
    return instance(config);
  }
}

export default new Service();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
Last Updated: 11/16/2021, 1:59:22 PM