Search code examples
javascriptvue.jsvue-routervuex

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.


Solution

  • I assume that you want to show a loader when a http request is on progress.

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

    Note that I am using axios in the example, but the logic works with other htpp libraries or fetch