Tick-Tack
Tick-Tack

Reputation: 213

Problems with the work of preloader vue.js

I'm trying to make showing preloader when i go from one component to another. I use this preloader. I create file loader.js and write there:

import Vue from 'vue';
import Loading from 'vue-loading-overlay';
import 'vue-loading-overlay/dist/vue-loading.css';

Vue.use(Loading);

let loader = Vue.$loading.show({
    loader: 'dots',
    color: '#5D00FF',
    zIndex: 999,
}); 
function loaderStart() {
    loader;
}
function loaderEnd() {
    loader.hide();
}

export default {loaderStart, loaderEnd}

loader,js i import to the index.js and there i write when i want to call loader start but it does not starting(withoun if in beforeResolve preloader is working). Here is index.js:

import Vue from 'vue'
import Router from 'vue-router'
import Authorization from '@/components/Authorization'
import Main from '@/components/Main'
import loader from './loader'

Vue.use(Router)

const router = new Router({
    routes: [
    {
        path: '/',
        name: 'Main',
        component: Main,
    },
    {
        path: '/authorization',
        name: 'Authorization',
        component: Authorization
    }
  ]
})
router.beforeResolve((to, from, next) => {
    if(to.path) {
        loader.loaderStart()
    }
    next()
});
router.afterEach((to, from) => {
    loader.loaderEnd()
});
export default router;

Please, help me find the problem

Upvotes: 2

Views: 1733

Answers (1)

Max Sinev
Max Sinev

Reputation: 6019

  1. Your current loader will appear just once because you called show method once as well. You need to invoke show method every loaderStart call and store the loader:

    let loader = null;
    function loaderStart() {
        // it would be better to extract these values as constants 
        loader = Vue.$loading.show({
             loader: 'dots',
             color: '#5D00FF',
             zIndex: 999,
        }); 
    }
    function loaderEnd() {
        loader.hide();
    }
    
  2. Probably you have some async components since you added loader to routing logic, so you should use the beforeEach hook instead of the beforeResolve one.

    router.beforeEach((to, from, next) => {
        loader.loaderStart()
        next()
    });
    router.afterEach((to, from) => {
       loader.loaderEnd()
    });
    

Loader API docs (show method)

Vue-router guards

Vue-router navigation flow

Upvotes: 4

Related Questions