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

标签 javascript vue.js vuejs2 axios

我目前正在构建一个 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();
});

最佳答案

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

demo

关于javascript - axios ajax,发出ajax请求时显示加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50768678/

相关文章:

vuejs2 - 如何在vue2-daterange-picker中实现 “Clear”按钮?

javascript - 我应该总是在浏览器中测试 JS 吗?

javascript - Bootstrap datepicker 日期比较错误(英国/美国格式错误)

javascript - 如何删除具有相同 url 的 div 并仅保留值?

css - 如何使用 Vue.js 在 CSS 网格中显示元素

webpack - Vuejs : Cannot find module "."

vuejs2 - 每次在另一个组件上输入时,都会执行Vue prop验证

javascript - 无法从类的方法调用构造函数中声明的属性

asp.net-mvc - 我可以在不使用 WebPack 的情况下向现有应用程序添加 Vue 单文件组件吗?

javascript - VueJS 在内联模板组件中重新编译 HTML