Axios ajax, show loading when making ajax request

前端 未结 3 910
遇见更好的自我
遇见更好的自我 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:59

    I think you are on the right path with dispatch event when ajax call start and finish.

    The way that I think you can go about it is to intercept the XMLHttpRequest call using axios interceptors like so:

    axios.interceptors.request.use(function(config) {
      // Do something before request is sent
      console.log('Start Ajax Call');
      return config;
    }, function(error) {
      // Do something with request error
      console.log('Error');
      return Promise.reject(error);
    });
    
    axios.interceptors.response.use(function(response) {
      // Do something with response data
      console.log('Done with Ajax call');
    
      return response;
    }, function(error) {
      // Do something with response error
      console.log('Error fetching the data');
      return Promise.reject(error);
    });
    
    function getData() {
      const url = 'https://jsonplaceholder.typicode.com/posts/1';
      axios.get(url).then((data) => console.log('REQUEST DATA'));
    }
    
    function failToGetData() {
      const url = 'https://bad_url.com';
      axios.get(url).then((data) => console.log('REQUEST DATA'));
    }
    
    
    
    

提交回复
热议问题