1. Why use lazy loading of routes
In order to give customers a better customer experience, the first screen component loads faster and solves the white screen problem .
Lazy loading can divide the page and load the page when needed, which can effectively share the loading pressure on the homepage and reduce the loading time of the homepage .
2. Definition
Lazy loading is simply lazy loading or on-demand loading , that is, loading when needed .
Three, use
There are two commonly used lazy loading methods: using vue asynchronous components and import in ES
1. Without lazy loading, the routing code in vue is as follows
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'HelloWorld',
component:HelloWorld
}
]
})
2. Vue asynchronous components implement lazy loading
The method is as follows: component: resolve=>(require(['the address of the route that needs to be loaded']), resolve)
import Vue from 'vue'
import Router from 'vue-router'
/* 此处省去之前导入的HelloWorld模块 */
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'HelloWorld',
component: resolve=>(require(["@/components/HelloWorld"],resolve))
}
]
})
3. The import method proposed by ES, ( ------ most commonly used------)
The method is as follows: const HelloWorld = () =>import('The address of the module that needs to be loaded')
(Without { }, it means direct 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
}
]
})
4. Lazy loading of components
Same as lazy loading of routes,
1. The writing method in the original component
<template>
<div class="hello">
<One-com></One-com>
1111
</div>
</template>
<script>
import One from './one'
export default {
components:{
"One-com":One
},
data () {
return {
msg: 'Welcome to Your Vue.js App'
}
}
}
</script>
2. const method
<template>
<div class="hello">
<One-com></One-com>
1111
</div>
</template>
<script>
const One = ()=>import("./one");
export default {
components:{
"One-com":One
},
data () {
return {
msg: 'Welcome to Your Vue.js App'
}
}
}
</script>
3. Asynchronous method
<template>
<div class="hello">
<One-com></One-com>
1111
</div>
</template>
<script>
export default {
components:{
"One-com":resolve=>require(['./one'],resolve)
},
data () {
return {
msg: 'Welcome to Your Vue.js App'
}
}
}
</script>