Axios ajax, show loading when making ajax request

前端 未结 3 853
遇见更好的自我
遇见更好的自我 2021-02-01 06:48

I\'m currently building a vue app and Im using axios. I have a loading icon which i show before making each call and hide after.

Im just wondering if there is a way to d

3条回答
  •  别那么骄傲
    2021-02-01 06:58

    I would setup Axios interceptors in the root component's created lifecycle hook (e.g. App.vue):

    created() {
      axios.interceptors.request.use((config) => {
        // trigger 'loading=true' event here
        return config;
      }, (error) => {
        // trigger 'loading=false' event here
        return Promise.reject(error);
      });
    
      axios.interceptors.response.use((response) => {
        // trigger 'loading=false' event here
        return response;
      }, (error) => {
        // trigger 'loading=false' event here
        return Promise.reject(error);
      });
    }
    

    Since you could have multiple concurrent Axios requests, each with different response times, you'd have to track the request count to properly manage the global loading state (increment on each request, decrement when each request resolves, and clear the loading state when count reaches 0):

    data() {
      return {
        refCount: 0,
        isLoading: false
      }
    },
    methods: {
      setLoading(isLoading) {
        if (isLoading) {
          this.refCount++;
          this.isLoading = true;
        } else if (this.refCount > 0) {
          this.refCount--;
          this.isLoading = (this.refCount > 0);
        }
      }
    }
    

    demo

提交回复
热议问题