Technology Sharing

Three ways to implement on-demand routing loading (lazy routing loading) in Vue projects

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

  1. When using vue-router to configure routes, you can use asynchronous components to load routes on demand. Asynchronous components are loaded only when the route is accessed, thus achieving the effect of on-demand loading. It should be noted that the use of asynchronous components requires the use of webpack's dynamic import syntax. For example:
  1. const Home = () => import(/* webpackChunkName: "home" */ './views/Home.vue')
  2. const routes = [
  3. {
  4. path: '/',
  5. name: 'Home',
  6. component: Home
  7. }
  8. ]

  1. Use Vue's asynchronous component factory function Vue provides an asynchronous component factory function to implement on-demand loading of routes. When using VueRouter to configure routes, you can usecomponent: () => import('./views/Home.vue')To define asynchronous components. In this way, the corresponding components will be dynamically loaded when the route is accessed.
  1. const routes = [
  2. {
  3. path: '/',
  4. name: 'Home',
  5. component: () => import('./views/Home.vue')
  6. }
  7. ]

  1. Using the import function of the dynamic import component Using the import function of ES6, you can implement on-demand loading of routes in vue-router. When configuring routes, you can usecomponent: () => import('./views/Home.vue')To define an asynchronous component.
  1. const routes = [
  2. {
  3. path: '/',
  4. name: 'Home',
  5. component: () => import('./views/Home.vue')
  6. }
  7. ]

The above three methods can all achieve on-demand loading of routes. The specific method you choose depends on your personal preferences and project requirements.