Axios Ajax,在发出Ajax请求时显示加载 [英] Axios ajax, show loading when making ajax request

查看:215
本文介绍了Axios Ajax,在发出Ajax请求时显示加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用axios构建一个vue应用程序和Im.我有一个正在加载的图标,在拨打每个电话之前都会显示该图标,之后会隐藏.

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 do this globally so I dont have to write the show/hide loading icon on every call?

这是我现在拥有的代码:

This is the code I have right now:

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文档中看到了拦截器",但是II不知道它们是全局的还是每次调用的.

I have seen on the axios docs there are "interceptors" but II dont know if they are at a global level or on each call.

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

I also saw this post for a jquery solution, not sure how to implement it on vue though:

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

推荐答案

我将设置 Axios拦截器在根组件的created生命周期挂钩中(例如App.vue):

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);
  });
}

由于您可能有多个并发的Axios请求,每个请求具有不同的响应时间,因此您必须跟踪请求计数以正确管理全局加载状态(每个请求的递增,每个请求的解析时的递减以及清除加载计数达到0时的状态):

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);
    }
  }
}

演示

这篇关于Axios Ajax,在发出Ajax请求时显示加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆