There are two common lazy loading modes for routes and components:

Component: resolve=>([‘ address of route ‘, resolve])

Const HelloWorld = () =>import(‘ address of module to load ‘)

1. Lazy route loading


1.1 Why Route Lazy Loading is Used?

To provide better customer experience, the first screen component can be loaded faster to solve the problem of blank screen.

1.2 define

Lazy loading is simply lazy loading or on-demand loading, that is, loading when needed.

1.3 the use of

No lazy loading, 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
        }
    ]
})
Copy the code

Vue asynchronous components implement lazy loading

Component: resolve=>(require([‘ address of route to load ‘]), resolve)

Import Vue from 'Vue' import Router from 'vue-router' /* Omit HelloWorld module */ vue. use(Router) export default new Router({ routes: [ { path: '/', name: 'HelloWorld', component: resolve=>(require(["@/components/HelloWorld"],resolve)) } ] })Copy the code

ES proposed import method (—— most commonly used ——)

Const HelloWorld = () =>import(‘ module address to load ‘)

import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'HelloWorld',
      component: ()=>import("@/components/HelloWorld")
    }
  ]
})
Copy the code

Webpack provides require.ensure()

{
  path: '/home',
  name: 'Home',
  component: r => require.ensure([],() =>  r(require('@/components/HelloWorld')), 'home')
}
Copy the code

2. Lazy loading of components


Written in the original component

<template>
  <div class="hello">
    <One-com></One-com>
  </div>
</template>

<script>
import One from './one'
export default {
  components:{
    "One-com":One
  },
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  }
}
</script>
Copy the code

ES proposes the import method

<template>
  <div class="hello">
    <One-com></One-com>
  </div>
</template>

<script>
export default {
  components:{
    "One-com": ()=>import("./one");
  },
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  }
}
</script>
Copy the code

Asynchronous methods

<template>
  <div class="hello">
    <One-com></One-com>
  </div>
</template>

<script>
export default {
  components:{
    "One-com":resolve=>(['./one'],resolve)
  },
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  }
}
</script>
Copy the code

Click to view the original article

If this article is helpful to you, thank you for your careful heart, your support is my motivation to continue to create! Finally: writing is not easy, if you want to cut, please indicate the source of reprint.