前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >浅谈vue+element全局loading加载

浅谈vue+element全局loading加载

作者头像
小丑同学
发布2020-09-21 15:17:40
6.5K0
发布2020-09-21 15:17:40
举报
文章被收录于专栏:小丑的小屋小丑的小屋

前言

在我们的平时的工作中,在前后端交互的时候,为了提高页面的观赏性和用户的体验,我们会在页面上添加loading来阻止用户操作来等待接口的返回,这个时候我们会考虑到全局loading还是局部loading,下面小编总结了一下,在开发中自己用到的方法,一起共享。

今天的工作任务是什么?

boss,完成全局loading加载的封装

01

用到的插件

1、element-ui-->ui库

2、lodash--->高效的JavaScript库

3、axios--->基于promise的http库

准备工作安装:

代码语言:javascript
复制
$ npm i element-ui -S
$ npm i lodash -S
$ npm i axios -S

02开启loading

首先我们需要引入element-ui的Loading组件,这个组件有两种调用方式:

1、通过指v-loading

2、通过服务Loading.service();

样式见下图:

api:https://element.eleme.cn/#/zh-CN/component/loading

代码语言:javascript
复制
import { Loading } from "element-ui";
import _ from 'lodash';

let loading = null;    //设置全局变量loading
let needRequestCount = 0;   //设置全局的请求总数

 //开启loading状态
const startLoading = (headers={}) => {
  loading = Loading.service({
    lock: true,   //是否锁定屏幕的滚动
    text: headers.text||"加载中……",   //loading下面的文字
    background: "rgba(0, 0, 0, 0.7)",   //loading的背景色
    target:headers.target||"body"    //loading显示在容器
  });
};

03关闭loading

在关闭loading的时候小编为了防止loading的闪动,这里采用了防抖的方法,防抖的计时一般采用300-600ms之前为最佳,在关闭loading的之后,我们要注意全局变量导致的V8垃圾回收机制,把没用的变量清空为null

代码语言:javascript
复制
//关闭loading状态
const endLoading = _.debounce(() => {
  loading.close();
  loading = null;
},300);

04对多次请求loading的开启

在这里,小编在方法中设置了headers的参数,这个参数的用途在于,在我们请求的时候我们不用的接口和方法可能用到的样式和文字不同,这个时候我们可以通过这个参数来传递

代码语言:javascript
复制
export const showScreenLoading=(headers)=>{
   if(needRequestCount == 0&&!loading){
    startLoading(headers);
   }
   needRequestCount++;
}

05对多次请求loading的关闭

在关闭的方法中,小编使用了一个Math.max()取最大值的方法,是为了保险取到的needRequestCount是0

代码语言:javascript
复制
export const hideScreenLoading=()=>{
    if(needRequestCount<=0)  return 
    needRequestCount--;
    needRequestCount = Math.max(needRequestCount, 0);
    if(needRequestCount===0){
        endLoading()
    }
}

06在请求中设置loading

在这里,我们使用的是axios的请求拦截器,如果不懂axios请求拦截器的童鞋可以看小编上一篇文章谈谈Vue开发过程中用到的插件

我们可以在headers的参数里设置showLoading属性来灵活的设置loading的显示和隐藏

代码语言:javascript
复制
 //请求拦截器
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);
   }
);

07在响应中设置loading

在这里,小编用了一个setTimeout定时器是为了模拟请求异步返回,查看loading的状态,在开发中我们可以去掉

代码语言:javascript
复制
 //响应拦截器
 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);
 }

此处应该有掌声

08完整的代码

Q

我可以直接用吗?

小丑

开箱即用,直接带走,就问你香不香

代码语言:javascript
复制
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();
代码语言:javascript
复制
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 {};
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2020-07-23,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 小丑的小屋 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档