美文网首页程序员
vue路由懒加载

vue路由懒加载

作者: snow_in | 来源:发表于2018-12-05 15:12 被阅读0次

    何为懒加载

    一个懒字道出了真谛,就是不一次性给你所有资源,什么时候要什么时候给。在我们的系统中就是当用到某个资源时再加载,随用随载(好啰嗦。。。)

    为什么需要?

    像vue这种单页应用,不做懒加载把所有资源打包成一个文件,当项目越做越大时打包出来的文件也越大。用户使用网站时由于文件太大,加载时间过长出现白屏,严重挑战用户的耐心,用户等不了就会关掉网站不看了,这不就损失用户了嘛。

    怎么做?

    既然要随用随载,就得把原来打进一个文件里面的资源拆分出来。那以什么作为分割点呢?如何拆分呢?既然是路由懒加载,就把路由变化时需要的资源作为一个Chunk。

    修改webpack配置:

    entry: {
        app: './src/main.js'
      },
      output: {
        path:  path.resolve(__dirname, '../dist'),
        filename: 'js/[name].[chunkhash].js',
        chunkFilename: 'js/[name].[chunkhash].js'
      },
    
    
    filename: 编译生成的js文件名,对应entry里面的文件。在上面的代码中就是app.[chunkhash].js
    chunkFilename: 非入口(non-entry) chunk 文件的名称
    

    修改路由:

    {
      path: '/dispatch-center',
      name: '',
      component: Main,
      children: [
        { path: 'suyun/auto/:resourceId', name: 'dispatch_center', component: () => import('../pages/dispatch/suyun/DispatchCenterComponent.vue') },
        { path: 'suyun/region-analysis', name: 'region_analysis', component: () => import('../pages/dispatch/suyun/RegionAnalysisTool.vue') },
        { path: 'suyun/balance', name: 'balance', component: () => import('../pages/dispatch/suyun/SuYunBalance.vue') },
        { path: 'suyun/business-manage', name: 'business_manage', component: () => import('../pages/dispatch/suyun/SuYunBusinessManage.vue') }
      ]
    }
    

    没修改前:

    {
      path: '/dispatch-center',
      name: '',
      component: Main,
      children: [
        { path: 'suyun/auto/:resourceId', name: 'dispatch_center', component: '../pages/dispatch/suyun/DispatchCenterComponent.vue' },
        { path: 'suyun/region-analysis', name: 'region_analysis', component: '../pages/dispatch/suyun/RegionAnalysisTool.vue' },
        { path: 'suyun/balance', name: 'balance', component: '../pages/dispatch/suyun/SuYunBalance.vue' },
        { path: 'suyun/business-manage', name: 'business_manage', component: '../pages/dispatch/suyun/SuYunBusinessManage.vue' }
      ]
    }
    
    

    可以看出最主要的就是组件用import导入。
    然后看一下打包后的结果:


    router1.png

    路由部分我们用import导入了四个组件,然后红框部分就多了四个chunk.
    没使用懒加载之前:


    router2.png
    可以看到就没有那些chunk。

    首次进入系统时加载的资源:


    router3.png

    切换路由后:


    router4.png
    可以看到路由变化后又加载了需要的资源。

    内容就到这里啦,如有不对的地方欢迎指教哦~

    相关文章

      网友评论

        本文标题:vue路由懒加载

        本文链接:https://www.haomeiwen.com/subject/gvjscqtx.html