Vue 2 / Vue CLI 3:创建异步单个文件组件

时间:2018-09-08 16:28:58

标签: vue.js webpack vue-router vue-cli-3

我使用了Vue-CLI 3,并告诉我要使用vue-router。它在创建的routes.js中生成这种类型的Webpack导入语句。

// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "about" */ './views/About.vue')

我继续创建四个视图。一些视图调用内部的组件。

Home.vue (Home page and default route at '/')
About.vue
Contact.vue
Photos.vue

我已在route.js中使About,Contact和Photos异步

import Home from './views/Home.vue';

/* name = named routes */
export const routes = [
    {
        path: '/',
        component: Home,
        name: 'home'
    },
    {
        path: '/photo/:id',
        // component: Photo,
        component: () => import(/* webpackChunkName: "Photo" */ './views/Photo.vue'),
        name: 'photo'
    },
    {
        path: '/about',
        component: () => import(/* webpackChunkName: "About" */ './views/About.vue'),
        // component: About,
        name: 'about'
    },
    {
        path: '/contact',
        // component: Contact,
        component: () => import(/* webpackChunkName: "Contact" */ './views/Contact.vue'),
        name: 'contact'
    },
    {
        /* Wildcard path to catch all other paths */
        path: '*',
        redirect: '/'
    }
];

当我进行构建时,Vue CLI确实会创建其他JS和CSS块(关于。[hash] .js等)。但是,当我加载Home路由时,这些其他块将根据Chrome的devtools进行加载,但是“响应”选项卡中也没有任何内容。然后,当我访问“关于”,“联系”或“照片”路线时,浏览器将加载这些块,但是现在“响应”选项卡中有一些内容。

异步是否按预期工作?

谢谢。

1 个答案:

答案 0 :(得分:0)

我想我可能已经知道我的本地路线上的这些额外电话是什么。 Webpack有一个可以打开预取的配置。我猜Vue CLI或Webpack的默认设置是启用预取。

https://webpack.js.org/guides/code-splitting/#prefetching-preloading-modules

https://medium.com/webpack/link-rel-prefetch-preload-in-webpack-51a52358f84c

Vue论坛上有人向我指出了Vue-CLI文档:  https://cli.vuejs.org/guide/html-and-static-assets.html#prefetch