zoukankan      html  css  js  c++  java
  • vue中路由按需加载的几种方式

    使用vue-cli构建项目后,我们会在Router文件夹下面的index.js里面引入相关的路由组件,如:

    import Hello from '@/components/Hello'
    import Boy from '@/components/Boy'
    import Girl from '@/components/Girl'
    

    普通加载的缺点:

    webpack在打包的时候会把整个路由打包成一个js文件,如果页面一多,会导致这个文件非常大,加载缓慢

    1、require.ensure()实现按需加载

    • 语法:
    require.ensuire(dependencies:String[],callback:function(require),errorCallback:function(error),chunkName:String)
    
    • vue中使用:
    const List = resolve =>{ require.ensure([],()=>{ resolve(require('./list')) },'list') }
    

    2、vue异步组件技术

    在router中配置,使用这种方法可以实现按需加载,一个组件生成一个js文件

    • vue中使用:
    {
    path: '/home',
    name: 'home',
    component:resove => require(['@/components/home'],resolve)
    }
    

    3、使用动态的import()语法(推荐使用这种)

    • vue中使用:
    //没有指定webpackChunkName,每个组件打包成一个js文件
    const test1 = ()=>import('@/components/test1.vue') 
    const test2 = ()=>import('@/components/test2.vue')
    
    //指定了相同的webpackChunkName,会合并打包成y一个js文件
    const test3 = ()=>import(/* webpackChunkName:'grounpTest' */ '@/components/test3.vue') 
    const test4 = ()=>import(/* webpackChunkName:'grounpTest' */ '@/components/test4.vue')
    
    const router = new VueRouter({
        routes: [
            { path: '/test1', component: test1 },
            { path: '/test2', component: test2 },
            { path: '/test3', component: test3 },
            { path: '/test4', component: test4 }
        ]
     })
    

    注:

    • /* webpackChunkName: 'grounpTest' */使用命名chunk,一个特殊的注释语法来提供 chunk name (需要 Webpack > 2.4)
  • 相关阅读:
    c#基础之集合
    找出子字符串在字符串中的所有索引
    c# 排序
    C#基础之枚举
    验证用户名不为空并且不存在
    验证用户名和密码,输入三次不正确就锁定账号
    c#基础
    linux使用
    python之logging模块
    手写MyBatis,纯手工打造开源框架(第三篇:运筹帷幄)
  • 原文地址:https://www.cnblogs.com/sgs123/p/10442450.html
Copyright © 2011-2022 走看看