代码之家  ›  专栏  ›  技术社区  ›  Valor_ user3379466

如何在路由器中正确延迟加载vuejs组件

  •  4
  • Valor_ user3379466  · 技术社区  · 7 年前

    我在路由器中加载组件时遇到问题

    这是我的router/index.js文件

    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 }
        }
    });
    

    这是我用来存储路由的routes.js文件

    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')
                }
            ]
        }
    ]
    

    问题是我一直在犯错误

    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 | 
    

    我也尝试过以这种方式加载,但我一直收到相同的错误

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

    然后路线看起来像

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

    但问题看起来是一样的。

    谁能帮我弄清楚,我错过了什么。如果您需要任何其他信息,请让我知道,我会提供。非常感谢。

    2 回复  |  直到 7 年前
        1
  •  3
  •   Pulkit Aggarwal    7 年前

    const Test = resolve => require(['@/components/Test/index'], resolve);
    
        2
  •  0
  •   Valor_ user3379466    7 年前

    最后,我找到了一个解决方案,用于使用导致我出现问题的上层语法。 因此,如果要以这种方式导入组件

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

    首先,您需要安装

    npm install --save-dev babel-plugin-syntax-dynamic-import
    

    {
      "plugins": ["syntax-dynamic-import"]
    }
    

    然后开始你的npm,无论你是如何开始的 npm run dev

    推荐文章