懒加载:又叫延时加载,即在需要的时候进行加载,随用即载
使用懒加载的原因:
像vue这种(spy)单页面应用,如果没有使用到懒加载,webpack打包的文件过大,造成进入首页时,加载的资源过多,时间过长,即使做了loading也不利于用户体验,而运用懒加载可以将页面进行划分,需要的时候加载页面,可以有效的分担首页所承担的加载压力,减少首页加载事件,简单来说就是进入首页不用一次加载过多资源造成时间过长
懒加载的使用方法:
ES 提出的import方法,(------最常用------)方法如下:const HelloWorld = ()=>import('需要加载的模块地址')
(不加 { } ,表示直接return)
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
const HelloWorld = ()=>import("@/components/HelloWorld") //推荐奖这种 简洁直观
export default new Router({
routes: [
{
path: '/',
name: 'HelloWorld',
component:HelloWorld
}
]
})
vue异步组件实现懒加载 方法如下:component:resolve=>(require(['需要加载的路由的地址']),resolve)
import Vue from "vue";
import VueRouter form "vue-router";
Vue.use(VueRouter);
export default new Router({
mode:"history",
routes:[
{
path: '/',
name: 'HelloWorld',
component: resolve=>(require(["../components/HelloWorld"],resolve))
},
{
path:'/Aboutus', //有children的不写name
meta: {
title: '关于我们'
},
children:[
{
path:'', //默认子路由 name写在默认子路由
name:'Aboutus',
component:resolve=>(require(["../components/Study"],resolve))
},
{
path:'/Study',
name:'Study',
component:resolve=>(require(["../components/Study"],resolve))
},
{
path:'/Work',
name:'Work',
component:resolve=>(require(["../components/Work"],resolve)),
meta:{
title:'work'
}
},
],
component:Aboutus
},
]
})
index.js
import Vue from 'vue';
import Router from 'vue-router';
import routers from './router';
const router = new Router({
routes: routers
})
router.js:适用后台管理(头部底部固定 左侧菜单 右侧内容点击)
export default [
{
path: "/",
redirect: "/Login",
},
{
path: '/Login',
name: 'Login',
component: (resolve)=>require(["../Pages/Login/Login.vue"],resolve),
meta:{
title:'xx'
}
},
{
path: '/Test', //和login同级 全新内容页面 不放在路由嵌套里面
name: 'Test',
component: (resovle) => require(["../Pages/Test/Test.vue"], resovle),
meta: {
requireAuth: true,
title: 'xxxx'
},
},
{
path:'/Home', //头部导航内容固定 就嵌套加左边内容嵌套
//name:'Home', //有children 不需要写name
component:(resolve)=>require(["../pages/Home/Home.vue"],resolve),
meta:{
requireAuth:true,
},
children:[
{
path:'/',
//name:'welcome', //需要左边菜单固定 就接着嵌套加右边内容
//有children 不需要写name
component:(resovle)=>require(["../pages/Home/welcome/welcome.vue"],resovle),
meta:{
requireAuth:true,
title:'xxx'
},
children:[
{
path:'', //默认子路由
name:'welcome',
component:welcomehome
},
{
path:'/welcomehome', // 右侧内容
name:'welcomehome',
component: (resovle)=>require(["../pages/home/welcomehome/welcomehome.vue"],resovle),
meta:{
requireAuth:true,
title:'xxx'
},
},
]
},
]
},
{
path: "*",
name: "error_404",
meta: {
title: "404"
},
component: (resolve) => require(["../error-page/404.vue"], resolve)
}
]
页面:记得加