栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

vue中路由按需加载的几种方式

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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.ensuire([],()=>{ resolve(require('./list')) },'list') }

ps:会报错,不知道如何解决,知道的朋友还请告知一下,报错内容如下:

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( '@/components/test3.vue') 
const test4 = ()=>import( '@/components/test4.vue')const router = new VueRouter({   
 routes: [
        { path: '/test1', component: test1 },
        { path: '/test2', component: test2 },
        { path: '/test3', component: test3 },
        { path: '/test4', component: test4 }
    ]
 })

注:

  • 使用命名chunk,一个特殊的注释语法来提供 chunk name (需要 Webpack > 2.4)

作者:smile_or

原文链接:https://www.cnblogs.com/sgs123/p/10442450.html


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/245623.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号