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', ponent:About},{path:'/index', ponent:Index},{path:'/home', ponent:Home}
3.webpack提供的require.ensure()
vue-router配置路由,使用webpack的require.ensure技术,也可以实现按需加载。
这种情况下,多个路由指定相同的chunkName,会合并打包成一个js文件。
/*组件懒加载方案三:webpack提供的require.ensure()*/{path:'/home',name:'home', ponent:r=>require.ensure([],()=>r(require('@ponents/home')),'demo')},{path:'/index',name:'Index', ponent:r=>require.ensure([],()=>r(require('@ponents/index')),'demo')},{path:'/about',name:'about', ponent: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', ponent:list,name:'blog'}]})
关于“vue如何实现路由按需加载”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“vue如何实现路由按需加载”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注主机评测网行业资讯频道。
上一篇:MyBatisPlus?TypeHandler怎么自定义字段类型转换Handler
下一篇:C语言各种符号如何使用