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(/* 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)

注,来源:https://www.cnblogs.com/xiaomili/p/10779827.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值