How to properly lazy load vuejs components in router

问题: I'm having a problem lazy loading components in my router this is my router/index.js file import Vue from "vue"; import Router from "vue-router"; import routes from './...

问题:

I'm having a problem lazy loading components in my router

this is my router/index.js file

import Vue from "vue";
import Router from "vue-router";
import routes from './routes'

Vue.use(Router);

export default new Router({
    routes,
    mode: 'history',
    base: __dirname,
    scrollBehavior (to, from, savedPosition) {
        if (savedPosition) {
            return savedPosition
        }
        return { x: 0, y: 0 }
    }
});

And this is my routes.js file for storing routes

import {Trans} from '@/plugins/Translation'

function load(component) {
    return () => import(/* webpackChunkName: "[request]" */ `@/components/${component}.vue`)
}

// I have also tried this way
//Vue.component(
//  'async-webpack-example',
//  // The `import` function returns a Promise.
//  () => import('./my-async-component')
//)

export default [
    {
        path: '/:lang',
        component: {
            template: '<router-view></router-view>'
        },
        beforeEnter: Trans.routeMiddleware,
        children: [
            {
                path: "/",
                name: "Home",
                component: load('Home')
            },
            {
                path: "/contact",
                name: "Contact",
                component: load('Contact')
            },
            ...
            // Many more other routes
            ...
            {
                path: '*',
                redirect: load('404')
            }
        ]
    }
]

The problem is that I'm keep getting error

ERROR in ./src/router/routes.js
Module build failed: SyntaxError: Unexpected token (4:17)

  2 | 
  3 | function load(component) {
> 4 |     return () => import(/* webpackChunkName: "[request]" */ `@/components/${component}.vue`)
    |                  ^
  5 | }
  6 | 
  7 | 

I have also tried to load the this way, but I keep getting the same error

const Test = () => import('@/components/Test');

and then route looks like

{
   path: "/",
   name: "Home",
   component: Test
}

but the problem looks the same.

Can some one please help me figure out, what I'm missing. If you need any additional informations, please let me know and I will provide. Thank you


回答1:

I am using this syntax for lazy loading. Check this syntax this will resolve your problem.

const Test = resolve => require(['@/components/Test/index'], resolve);
  • 发表于 2018-12-27 20:24
  • 阅读 ( 215 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除