Vue routing lazy loading

Route lazy loading

When packaging and building an application, the Javascript package can become very large and affect page loading. It would be more efficient if we could divide the components corresponding to different routes into different code blocks, and then load the corresponding components when the route is accessed.

Combining Vue's asynchronous components and Webpack's code splitting function , it is easy to implement lazy loading of routing components.

First, an asynchronous component can be defined as a factory function that returns a Promise (the Promise returned by this function should resolve the component itself):

const Foo = () => Promise.resolve({ /* 组件定义对象 */ })

Second, in Webpack 2, we can use dynamic import syntax to define code split points:

import('./Foo.vue') // 返回 Promise

Note: If you are using Babel, you will need to add  syntax-dynamic-import plugins so that Babel can parse the grammar correctly.

Combining the two, this is how to define an async component that can be automatically code-split by Webpack.

const Foo = () => import('./Foo.vue')

Nothing needs to be changed in the routing configuration, just use as usual  Foo:

const router = new VueRouter({
  routes: [
    { path: '/foo', component: Foo }
  ]
})

Block components into groups

Sometimes we want to package all components under a route in the same async chunk. Just use  named chunks , a special comment syntax to provide the chunk name (requires Webpack > 2.4).

const Foo = () => import(/* webpackChunkName: "group-foo" */ './Foo.vue')
const Bar = () => import(/* webpackChunkName: "group-foo" */ './Bar.vue')
const Baz = () => import(/* webpackChunkName: "group-foo" */ './Baz.vue')

Webpack will combine any async module with the same chunk name into the same async chunk.

 

When not using lazy loading

The http request is as follows. Because the routing information is all in the app, it will not be requested again. If the routing component is relatively small, not using lazy loading can reduce the network request time. If the routing component is relatively large and the frequency of use is not high, you can use lazy loading. , and ask for it when needed

 

Use lazy loading

The http request is as follows, which will only be loaded when using routing

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324944513&siteId=291194637