vue-router懒加载的三种方式

1.vue-router懒加载定义

当路由被访问的时候才加载对应组件

2.vue-router懒加载作用

当构建的项目比较大的时候,懒加载可以分割代码块,提高页面的初始加载效率。

3.vue-router懒加载实现

第一种写法

1
2
3
4
5
6
7
const routers = [
{
path: '/',
name: 'index',
component: (resolve) => require(['./views/index.vue'], resolve)
}
]

第二种写法

1
2
3
4
5
6
7
8
const Index = () => import(/* webpackChunkName: "group-home" */  '@/views/index')
const routers = [
{
path: '/',
name: 'index',
component: Index
}
]

详见:路由懒加载

第三种写法:

1
2
3
4
5
6
7
8
const Index = r => require.ensure([], () => r(require('./views/index')), 'group-home');
const routers = [
{
path: '/',
name: 'index',
component: Index
}
]

详见:Vue-Router + Webpack 路由懒加载实现

备注:

@/./有异曲同工之用
.vue后缀可省略
group-home是把组件按组分块打包, 可以将多个组件放入这个组中