Why lazy loading?
For single-page applications like Vue, if there is no routing lazy loading, the files packed by Webpack will be very large, resulting in too much content to load when entering the home page and a long white screen. Using routing lazy loading, pages can be divided and loaded only when needed. It can effectively share the load pressure borne by the home page and reduce the load time of the home page.
The following three methods are used to load vUE routes lazily
- Vue asynchronous components
- The ES6
import()
- The webpack
require.ensure()
Vue asynchronous components
This method mainly uses the asynchronous mechanism of Resolve and uses require instead of import to load on demand. Webpack4 dynamically adds lazy route loading, so you need to use this method to load; otherwise, an error will be reported.
export default new Router({
routes: [
{
path: '/home',
component: (resolve) => require(['@/components/home'], resolve)
},
{
path: '/about',
component: (resolve) => require(['@/components/about'], resolve)
},
],
})
Copy the code
require.ensure
This mode packs js separately with webpackChunkName in the argument.
export default new Router({
routes: [
{
path: '/home',
component: (resolve) => require.ensure([], () => resolve(require('@/components/home')), 'home')
},
{
path: '/about',
component: (resolve) => require.ensure([], () => resolve(require('@/components/about')), 'about')
},
],
})
Copy the code
ES6 import ()
Vue-router provides a method on the official website, which is understood to be the resolve mechanism of Promise. Because the Promise function returns the Promise as the Resolve component itself, we can use import to import the component.
export default new Router({
routes: [
{
path: '/home',
component: () => import('@/components/home')
},
{
path: '/about',
component: () => import('@/components/about')
},
],
})
Copy the code