SoFunction
Updated on 2025-04-07

Based on Vue + Axios, it realizes the automatic display of the shutdown effect of global Loading

Based on Vue + Axios, it realizes the automatic display of the shutdown effect of global Loading

Updated: March 14, 2024 08:43:34 Author: The Stupid Bird must fly first
In vue projects, we usually use Axios to interact with the background data. When we initiate a request, we often need to display a loading box (Loading) on ​​the page, and then automatically hide it after the data is returned. This article introduces the automatic display of the global Loading based on Vue + Axios. Friends who need it can refer to it.

Preface

existvueIn projects, we usually useAxiosCome to interact with the background data. When we initiate a request, we often need to display a load box on the page (Loading), and then automatically hide the data after it returns.To implement this function, we can manually display a load box before each request, and hide it after receiving the data. But if every request is to do this, it's a little troublesome., but as we all know, programmers are a creature that doesn't like trouble, so how do we make this step less complicated?

Below is ademoDemonstrate how to encapsulate a beltloadingEffectiveAxiosComponent, which can intercept requests and responses to achieveloadingAutomatically display and hide, and an error message pops up automatically when the request fails.

demo

Principle description

  • Control the display or hiding of loading through the interface provided by axios for request interception and response interception. At the same time, when the request fails, a message prompt box will automatically pop up to display an error message.
  • loadingEffectiveElement UIProvided inLoadingComponents to implement. The error message prompt box usesElement UIIn-houseMessageComponents to implement.
  • There is an internal counter to ensure that if there are multiple requests at the same time, there will be no multiple loadings at the same time, but only one. And loading will not be hidden after all requests are completed.
  • UseddebounceAnti-shake. Because sometimes you will encounter a new request immediately after a request is completed. This situation will cause continuousloadingTwice, and there is a flash in the middle. Avoid flickering through anti-shake.
  • All requests will be automatically available by defaultloadingEffect. If a request does not require itloadingEffects can be found in the request headershowLoadingSet asfalse
  • The defaultloadingThe effect is to cover thebodysuperior. If a request needs to be displayed on a specified elementloadingEffect, you can requestheadermiddleloadingTargetSet as the selector for this element.

Code implementation

import axios from 'axios';
import { Message,Loading } from 'element-ui';
import _ from 'lodash';
  
const http = ({
    baseURL:.BASE_URL, //Set the requested base url    timeout:40000 //Timeout time});
  
//loading
let loading;
  
//The number of requests currentlylet LoadingRequestCount = 0;
  
//Show loadingfunction showLoading(target) {
  if (LoadingRequestCount === 0 && !loading) {
    loading = ({
      lock: true,
      text: "loading",
      background: 'rgba(255, 255, 255)',
      target: target || "body"
    });
  }
  LoadingRequestCount++;
}
  
//Hide loadingfunction hideLoading() {
  LoadingRequestCount--;
  LoadingRequestCount = (LoadingRequestCount, 0); //Prevent situations less than 0 from happening  if (LoadingRequestCount === 0) {
    //Close loading    toHideLoading();
  }
}
  
//Anti-shakevar toHideLoading = _.debounce(()=>{
      ();
      loading = null;
    }, 100);
  
//Add a request interceptor(config => {
  //Display Loading is not displayed when the current request is set.  if( !== false){
    showLoading();
  }
  return config;
}, err => {
  //Display Loading is not displayed when the current request is set.  if( !== false){
    hideLoading();
  }
  ('Request failed!');
  //Top an error  return (err);
});
  
//Response Interceptor(
    response => {
      //Judge whether the current request is set to not display Loading (it is naturally no need to hide if it is not displayed)      if( !== false){
        hideLoading();
      }
      
      return response;
    },
    error => {
      //Judge whether the current request is set to not display Loading (it is naturally no need to hide if it is not displayed)      if( !== false){
        hideLoading();
      }
      
      if( &&  && ) {
        var jsonObj = ();
        ();
      }else{
        ();
      }
      return (error);
    }
);
  
export default http;

Conclusion

This is the article about implementing the automatic display of the shutdown effect of global Loading based on Vue + Axios. For more related Vue + Axios Loading, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!

  • Vue
  • Axios
  • Loading
  • automatic
  • closure

Related Articles

  • Interpretation of the relationship between ref tag attribute and $ref in vue

    This article mainly introduces the relationship between the ref tag attribute and $ref in vue, which has good reference value and hopes it will be helpful to everyone. If there are any mistakes or no complete considerations, I hope you will be very grateful for your advice
    2023-07-07
  • Vue Disables the forward and backward operation of the browser

    This article mainly introduces Vue's forward and backward operations to disable the browser, which is of good reference value and hopes to be helpful to everyone. Let's take a look with the editor
    2020-09-09
  • The solution is that the vue-admin-element project suddenly cannot get up.

    This article mainly introduces the solution that the vue-admin-element project suddenly cannot get up. It has good reference value and hopes it will be helpful to everyone. If there are any mistakes or no complete considerations, I hope you will be very grateful for your advice
    2022-10-10
  • A little knowledge about dynamic splicing of vue src paths

    This article mainly introduces the little knowledge about dynamic splicing of vue src paths, which is of good reference value and hopes to be helpful to everyone.
    2022-04-04
  • Solve the problem of using swiper plug-in in vue and the usage of swiper in vue

    Swiper is a sliding special effects plug-in created by pure JavaScript, which is aimed at mobile terminals such as mobile phones and tablets. This article mainly introduces the solution to the use of swiper plug-in in vue and the usage of swiper in vue. Friends who need it can refer to it
    2018-04-04
  • Configuration method and principle of Vue Router history mode

    This article mainly introduces the configuration method and principles of the Vue Router history mode. This article introduces you very detailed and has certain reference value. Friends who need it can refer to it.
    2019-05-05
  • Sample code for using Loading components in vue project

    This article mainly introduces the sample code of using the Loading component in the vue project, using the loding transition data loading time
    2018-08-08
  • Detailed explanation of Vuex modular use

    This article mainly introduces the detailed explanation of the modular use of Vuex. The example code is introduced in the article in detail, which has certain reference learning value for everyone's study or work. Friends who need it, please learn with the editor below.
    2019-07-07
  • A brief discussion on the solution to the inability to load vue-cli

    This article mainly introduces a brief discussion on the solution to the inability to load vue-cli. The editor thinks it is quite good. I will share it with you now and give you a reference. Let's take a look with the editor
    2017-11-11
  • The solution to the vue project has been around. Sockjs-node/info?t=XX

    sockjs-node is a JavaScript library that provides a cross-browser JavaScript API and creates a communication channel between a low-latency, full-duplex browser and web server. This article mainly introduces the solution that the vue project has always appeared sockjs-node/info?t=XX. Friends who need it can refer to it.
    2023-12-12

Latest Comments