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)
  • 相关阅读:
    deepin/uos和局域网其他机器无法ping通
    Ubuntu18.04完全卸载vscode
    批量拉取github组织或者用户的仓库
    vmware uos挂载windows共享目录
    清空容器另类方式
    time_t 时间格式化字符串
    条件变量condition_variable
    C++多维堆数组定义
    arm64 ubuntu18.04 bionic安装bcc tools
    win10下载编译chromium
  • 原文地址:https://www.cnblogs.com/sgs123/p/10442450.html
Copyright © 2011-2022 走看看