vue如何实现路由按需加载


这篇文章主要介绍了vue如何实现路由按需加载的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇vue如何实现路由按需加载文章都会有所收获,下面我们一起来看看吧。

为什么需要懒加载?

像vue这种单页面应用,如果没有应用懒加载,运用webpack打包后的文件将会异常的大,造成进入首页时,需要加载的内容过多,时间过长,会出啊先长时间的白屏,即使做了loading也是不利于用户体验,而运用懒加载则可以将页面进行划分,需要的时候加载页面,可以有效的分担首页所承担的加载压力,减少首页加载用时

  • vue异步组件

  • es提案的import()

  • webpack的require,ensure()

1 . vue异步组件技术 ==== 异步加载

vue-router配置路由 , 使用vue的异步组件技术 , 可以实现按需加载 .
但是,这种情况下一个组件生成一个js文件

{ path: '/home', name: 'home',ponent: resolve => require(['@ponents/home'],resolve) },

{ path: '/index', name: 'Index',ponent: resolve => require(['@ponents/index'],resolve) },

{ path: '/about', name: 'about',ponent: resolve => require(['@ponents/about'],resolve) }

非懒加载:

懒加载

2.组件懒加载方案二 路由懒加载(使用import)

const组件名=()=>import('组件路径');//下面2行代码,没有指定webpackChunkName,每个组件打包成一个js文件。/*constHome=()=>import('@ponents/home')constIndex=()=>import('@ponents/index')constAbout=()=>import('@ponents/about')*///下面2行代码,指定了相同的webpackChunkName,会合并打包成一个js文件。把组件按组分块constHome=()=>import(/*webpackChunkName:'ImportFuncDemo'*/'@ponents/home')constIndex=()=>import(/*webpackChunkName:'ImportFuncDemo'*/'@ponents/index')constAbout=()=>import(/*webpackChunkName:'ImportFuncDemo'*/'@ponents/about'){path:'/about',&nbspponent:About},{path:'/index',&nbspponent:Index},{path:'/home',&nbspponent:Home}

3.webpack提供的require.ensure()

vue-router配置路由,使用webpack的require.ensure技术,也可以实现按需加载。
这种情况下,多个路由指定相同的chunkName,会合并打包成一个js文件。

/*组件懒加载方案三:webpack提供的require.ensure()*/{path:'/home',name:'home',&nbspponent:r=>require.ensure([],()=>r(require('@ponents/home')),'demo')},{path:'/index',name:'Index',&nbspponent:r=>require.ensure([],()=>r(require('@ponents/index')),'demo')},{path:'/about',name:'about',&nbspponent:r=>require.ensure([],()=>r(require('@ponents/about')),'demo-01')}//r就是resolveconstlist=r=>require.ensure([],()=>r(require('..ponents/list/list')),'list');//路由也是正常的写法这种是官方推荐的写的按模块划分懒加载constrouter=newRouter({routes:[{path:'/list/blog',&nbspponent:list,name:'blog'}]})

关于“vue如何实现路由按需加载”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“vue如何实现路由按需加载”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注主机评测网行业资讯频道。


上一篇:MyBatisPlus?TypeHandler怎么自定义字段类型转换Handler

下一篇:C语言各种符号如何使用


Copyright © 2002-2019 测速网 www.inhv.cn 皖ICP备2023010105号
测速城市 测速地区 测速街道 网速测试城市 网速测试地区 网速测试街道
温馨提示:部分文章图片数据来源与网络,仅供参考!版权归原作者所有,如有侵权请联系删除!

热门搜索 城市网站建设 地区网站制作 街道网页设计 大写数字 热点城市 热点地区 热点街道 热点时间 房贷计算器