Vue:请求正在进行时显示加载器

时间:2018-03-19 05:53:17

标签: javascript vue.js vue-router vuex

我想实现以下流程:

当http请求正在进行时,显示加载程序。请求完成后隐藏加载程序。

2 个答案:

答案 0 :(得分:5)

我不确定我是否理解你,但我假设那样。当http请求正在进行时你想要一个加载器。所以我要展示逻辑。希望理解

<template>

    <div>

        <div v-if="loading">
            <!-- here put a spinner or whatever you want to do when request is on proccess -->
        </div>

        <div v-if="!loading">
            <!-- here is your application code -->
        </div>

    </div>

</template>

<script>
    import axios from 'axios'
    export default {
        data() {
            return {
                loading: false
            }
        },
        methods: {
            makeRequest () {
                this.loading = true //the loading begin
                axios.get('/example')
                .then(response => {
                    this.loading = false //the loading stop when the response given from server
                    //do whatever with response
                })
                .catch(error => {
                    this.loading = false
                    //do whatever with response
                })
            }
        }
    }
</script>

希望你理解。有关信息,发送http请求我使用的是axios,我也在使用v-if,但在第二个div中你可以使用v-else

答案 1 :(得分:0)

仅适用于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: {

  }
}