[Vuejs]-Show loading screen to user when lazy loading vue

0👍

okay after doing some more in depth searching i finally found the solution

first you need to use vuex to pass along the variable or information and then you just hook it into router function like this

router.beforeEach((to, from, next)=>{
  store.commit('setLoading', true)
  next()
})
router.afterEach((to, from)=>{
  store.commit('setLoading', false)
})

and then in my app.vue files i just add this

<template>
<div>
    <!-- header -->
    <transition 
        enter-active-class="animated fadeInDown"
        leave-active-class="animated fadeOutUp"
        mode="out-in"
    >
        <router-view name="header"></router-view>
    </transition>
    
    <!-- body -->
    <transition 
        enter-active-class="animated fadeIn"
        leave-active-class=""
        mode="out-in"
    >
        <loading-page v-if="isLoading"></loading-page>
        <router-view v-else></router-view>
    </transition>
    
</div>
</template>

<script>
    import { mapGetters } from 'vuex';
    import loadingPage from "./views/loading.vue";

    export default {
        components: {
            loadingPage
        },
        computed:{
            ...mapGetters('global',{
                isLoading: 'isLoading'
            }),
        },
    }
</script>

and here is my loading screen, just a simple page with loading bar

<template>
    <div>
        <!-- page container -->
        <div class="page-content">
            <div class="content-wrapper">
                <div class="content">

                    <div class="card card-body">
                        <div class="progress">
                            <div class="progress-bar progress-bar-info progress-bar-striped progress-bar-animated" style="width: 100%">
                                <span class="sr-only">100% Complete</span>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
        </div>
        
    </div>
</template>

and for my vuex


export const global = {
  namespaced: true,
  
  // state
  state: {
    isLoading: '',
  },

  // getters
  getters: {
    isLoading: state => state.isLoading,
  },

  // actions
  actions: {

    // change data
    setLoading({commit}, type){
      commit('setLoading', type);
    },
  },

  // mutations
  mutations: {

    setLoading ( state, type ){
      state.isLoading = type;
    },
  }
}

then it will be just showing that loading screen whenever i navigate to other page that still not yet be loaded in user browser.

Leave a comment