懒加载也叫延迟加载,即在需要的时候进行加载,随用随载。
众所周知vue是一种应用于单页面开发的框架,像vue这种单页面应用,如果没有应用懒加载。造成进入首页时,需要加载的内容过多,时间过长,会出现一段时间的白屏,即使有loading也是不利于用户体验的;而运用懒加载则可以将页面进行划分,需要的时候加载页面,减少首页加载的用时。
非懒加载路由的写法:
import Vue from 'vue'
import Router from 'vue-router'
// 引入组件
import Home from '@/components/luyou/Home'
import About from "@/components/luyou/About";
import List from '@/components/dynamicRoute/List';
// 要告诉 vue 使用 Router
Vue.use(Router)
export default new Router({
routes: [
{ path: '/home',name: 'Home',component: Home,
children: [{name: 'List',path: "list",component: List}]
},
{ path: '/about',name: 'About',component: About },
{ path: '/', redirect: '/home' }
]
})
懒加载路由的写法:
(1). import()实现
import Vue from 'vue'
import Router from 'vue-router'
// 要告诉 vue 使用 Router
Vue.use(Router);
// const 组件名 = () => import('组件路径');
const Home = () => import(/* webpackChunkName: "homePage" */ '@/components/luyou/Home');
const List = () => import(/* webpackChunkName: 'homePage' */ '@/components/dynamicRoute/List');
const About = () => import(/* webpackChunkName: 'aboutPage' */ '@/components/luyou/About');
export default new Router({
routes: [
{
path: '/home',name: 'Home',component: Home,
children: [{ path: "list",component: List }]
},
{ path: '/about',name: 'About',component: About },
{ path: '/', redirect: '/home' }
]
})
注:没有指定webpackChunkName,每个组件打包成一个js文件,指定了相同的webpackChunkName,会合并打包成一个js文件,按组分块。
(2). require.ensure()实现
const Home = r => require.ensure([], () => r(require('@/components/luyou/Home')), 'homePage')
const List = r => require.ensure([], () => r(require('@/components/dynamicRoute/List')), 'homePage')
const About = r => require.ensure([], () => r(require('@/components/luyou/About')), 'aboutPage')
//或者
const api = {
Home : r => require.ensure([], () => r(require('@/components/luyou/Home')), 'homePage'),
List : r => require.ensure([], () => r(require('@/components/dynamicRoute/List')), 'homePage')
About : r => require.ensure([], () => r(require('@/components/luyou/About')), 'aboutPage')
}
require.ensure()接受三个参数:
require.ensure(dependencies:String [],
callback:function(require),
errorCallback:function(error),
chunkName:String)
参数1:的依赖关系是一个数组,代表了当前需要进来的模块的一些依赖;
参数2:回调就是一个回调函数;
参数3:是处理错误的回调;
参数4:chunkName则是指定打包的组块名称。