axios ajax,发出ajax请求时显示加载

新手上路,请多包涵

我目前正在构建一个 vue 应用程序,我正在使用 axios。我有一个加载图标,我在每次调用之前显示并在之后隐藏。

我只是想知道是否有办法在全球范围内做到这一点,所以我不必在每次通话时都写显示/隐藏加载图标?

这是我现在拥有的代码:

 context.dispatch('loading', true, {root: true});
axios.post(url,data).then((response) => {
        // some code
        context.dispatch('loading', false, {root: true});
    }).catch(function (error) {
        // some code
        context.dispatch('loading', false, {root: true});color: 'error'});
    });

我在 axios 文档上看到有“拦截器”,但我不知道它们是在全局级别还是在每次调用中。

我还看到了这篇关于 jquery 解决方案的帖子,但不确定如何在 vue 上实现它:

 $('#loading-image').bind('ajaxStart', function(){
    $(this).show();
}).bind('ajaxStop', function(){
    $(this).hide();
});

原文由 Brad 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 623
2 个回答

我会在根组件的 created 生命周期挂钩中设置 Axios 拦截器(例如 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);
  });
}

由于您可能有多个并发 Axios 请求,每个请求具有不同的响应时间,因此您必须跟踪请求计数以正确管理全局加载状态(每个请求递增,每个请求解决时递减,计数时清除加载状态达到 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);
    }
  }
}

演示

原文由 tony19 发布,翻译遵循 CC BY-SA 4.0 许可协议

我认为当 ajax 调用开始和结束时,您在调度事件的正确路径上。

我认为您可以采用的方法是使用 axios 拦截器拦截 XMLHttpRequest 调用,如下所示:

 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'));
}
 <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<button onclick="getData()">Get Data</button>
<button onclick="failToGetData()">Error</button>

原文由 Shahar 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题