Examples of 3 Methods for Lazy Loading of Routing in vue

  • 2021-08-10 06:44:13
  • OfStack

Preface

Routing lazy loading is very important when visiting pages, which can improve the loading speed of home pages and avoid white pages when loading. If there is no lazy loading, the files packaged by webpack will be very large.

import Load on Demand (Common) vue asynchronous component require. ensure () provided by webpack

1. import is loaded on demand (commonly used)

Allows different components to be packaged into a single asynchronous block, with the same webpackChunkName specified.

Block the components into components


const A = () => import(/* webpackChunkName: "group-A" */ '@/A/A.vue')
const B = () => import(/* webpackChunkName: "group-A" */ '@/A/B.vue')
const C = () => import(/* webpackChunkName: "group-A" */ '@/A/C.vue')

Note: If you are using babel, you need to install the syntax-dynamic-import plug-in for babel to parse syntax correctly.

2. vue asynchronous component

The asynchronous components of vue are used to realize on-demand loading, and each component generates one js file to realize lazy loading of components.


/* vue Asynchronous component  */
{ path: '/A', name: 'A', component: resolve => require(['@/components/A'],resolve) }

3. require. ensure () provided by webpack

vue-router configures routing, using require. ensure technology of webpack for on-demand loading.

In this case, multiple routes that specify the same chunkName are merged and packaged into a single js file.

Syntax: require. ensure (dependencies: String [], callback: function ([require]), [chunkName: String])

dependencies: Dependent Module Array

require: Callback function that passes 1 require parameter when called

chunkName: Module name, which is used to name and use when generating files at build time


const A= resolve => require.ensure([], () => resolve(require('@/components/A')), 'A');

Note: The module of requi. ensure will only be downloaded and will not be executed. The module will only be executed after the callback function uses require (module name).

Summarize


Related articles: