[Vuejs]-How can I add a loader before api request completed in Vue SPA

1👍

You could use an isLoading boolean to conditionally render the progress bar when true, and the rest of your component if false.

I see you have axios mentioned. Unlikely, but if you aren’t making any more API calls after the initial page load, you could create interceptors in your axios instance that set a piece of vuex state as true when the request begins, and false when it finishes. You could then just conditionally render your progress bar in App.vue when true, and your router-view when false.

import axios from 'axios'
import store from '@/store'

const api = axios.create({
  baseURL: 'URL',
})

api.interceptors.request.use(config => {
    store.commit('changeLoadingStatus', true)
    return config
  }, error => {
    // Handle errors
})

api.interceptors.response.use(response => {
    store.commit('changeLoadingStatus', false)
    return response
  }, error => {
    // Handle errors
})

export default api

👤shouri

0👍

I have not tried it myself but maybe you can try something like this

const router = new Router({
  routes: [
      { path: '/', name: 'home', component: Home },
      { path: '/about', name: 'about', component: About }
  ]
})

router.beforeResolve((to, from, next) => {
    // If this isn't an initial page load.
    if (to.name) {
        // Start the route progress bar.
        NProgress.start()
    }
    next()
})

router.afterEach((to, from) => {
    // Complete the animation of the route progress bar.
    NProgress.done()
})

Leave a comment