【问题标题】:Vue: Display Loader when request is in progressVue:请求正在进行时显示加载器
【发布时间】:2018-08-27 15:17:33
【问题描述】:

我想实现如下流程:

当一个 http 请求正在进行时,显示一个加载器。当请求完成时隐藏加载器。

【问题讨论】:

标签: javascript vue.js vue-router vuex


【解决方案1】:

我假设您想在 http 请求正在进行时显示加载器。

<template>

    <div>

        <div v-if="loading">
            <!-- here put a spinner or whatever you want to indicate that a request is in progress -->
        </div>

        <div v-else>
            <!-- request finished -->
        </div>

    </div>

</template>

<script>
    import axios from 'axios'

    export default {
        data: () => {
          loading: false
        },

        methods: {
          makeRequest () {
            this.loading = true //the loading begin
            axios.get('/example')
            .then(response => { ... }) // code to run on success
            .catch(error => { ... }) // code to run on error
            .finally(() => (this.loading = false)) // set loading to false when request finish
          }
        }
    }
</script>

请注意,我在示例中使用 axios,但该逻辑适用于其他 htpp 库或 fetch

【讨论】:

    【解决方案2】:

    仅适用于 Nuxt.js 用户

    roli 编写的示例很棒,但理想情况下您不想重复自己 对您提出的每个请求。所以我建议你这样做 感谢:https://stackoverflow.com/a/58084093/1031297

    添加 ['@nuxtjs/axios']....

    添加或修改 plugins/axios.js

    export default ({ app, $axios ,store }) => {      
      $axios.interceptors.request.use((config) => {
        store.commit("SET_DATA", { data:true, id: "loading" });
        return config;
      }, (error) => {
        return Promise.reject(error);
      });
    
      $axios.interceptors.response.use((response) => {
        store.commit("SET_DATA", { data:false, id: "loading" });
        return response;
      }, (error) => {
        return Promise.reject(error);
      });
    }
    

    商店正在

    export default {
      state: () => ({
        loading: false
      }),
      mutations: {
        SET_DATA(state, { id, data }) {
          state[id] = data
        }
      },
      actions: {
    
      }
    }
    

    【讨论】:

    • @vsync 正如我所说,它适用于 nuxt 用户。如果你不是 nuxt 用户,去别的地方挖或者自己动手做
    • 添加这些后,axios 请求会是什么样子?
    猜你喜欢
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    • 2011-12-14
    • 1970-01-01
    • 1970-01-01
    • 2020-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多