Vue: Display Loader when request is in progress

I want to implement a process as below:

When a http request is in progress, display a loader. When the requests finish hide the loader.

Answers:

Answer

I am not sure if i understand you,but i assuming that.You want a loader when a http request is on progress.So i am going to show the logic.Hope to understand

<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>

Hope you understand.For information, for sending http request i am using axios and also i am using v-if in both cases but in the second div you can use v-else

Answer

Only for Nuxt.js users

the example that roli wrote up is great, but ideally you don't want to repeat yourself on every request that you make. so I would suggest you do like this thanks to: https://stackoverflow.com/a/58084093/1031297

Add ['@nuxtjs/axios']....

Add or Modify 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);
  });
}

with the store being

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

  }
}

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.