[Vuejs]-Vue router shows lazy-loaded route components only once

0👍

Here is how i deal with lazy loading of router components
This will work only if you use babel/webpack/vue-cli etc… since its ES6

inside my router folder i have

index.js

import Vue from 'vue';
import Router from 'vue-router';
import lazyLoading from './lazyLoading';

Vue.use(Router);

const router = new Router({
    mode: 'history',
    linkActiveClass: 'active-route',
    routes: [
        {
            path: '/',
            name: 'app',
            components: {
                default: lazyLoading('YourComponent'), 
            },
        },
        {
            path: '/somepath',
            name: 'somename',
            components: {
                default: lazyLoading('YourSecondComponent'),
            },
        },
        {
            path: '*',
            redirect: '/',
        },
    ],
});

export default router;

If your component is with name index.vue inside folder do this.

Here adjust the import url to find the proper path in your project.

lazyLoading('YourFolder', true)

lazyloading.js

export default (name, index = false) => () => import(`../components/${name}${index ? '/index' : ''}.vue`);

Leave a comment