search
HomeWeb Front-endVue.jsHow to apply lazy loading of vue3 vite asynchronous components and routing

1. Preface

1-1. Three changes:

  • Changes in the asynchronous component declaration method: Vue 3.x adds a new auxiliary function defineAsyncComponent, Used to display the declaration of asynchronous components

  • The component option in the advanced declaration method of asynchronous components is renamed to loader

  • The component loading function bound by loader is not Then receive resolve and reject parameters, and must return a Promise

1-2. The reason for introducing the auxiliary function defineAsyncComponent:

Now, in Vue 3, due to the function Components are defined as pure functions, async component definitions need to be explicitly defined by wrapping them in a new defineAsyncComponent helper.

2. Comparison of Vue 2.x and Vue 3.x definitions

2-1. Comparison of asynchronous component/routing definitions

  • ##2-1 -1. In Vue 2.x, just declare an asynchronous component like this:

  • const asyncPage = () => import('./views/home.vue')
  • 2-1-2. In Vue 3.x, The import of asynchronous components requires explicit declaration using the auxiliary function defineAsyncComponent. As follows:

  • <template>
      <div>
        <h2 id="Async-nbsp-Components">Async Components</h2>
        <p>异步组件测试</p>
        <child />
      </div>
    </template>
    <script>
    import { defineAsyncComponent } from &#39;vue&#39;
    const child = defineAsyncComponent(() => import(&#39;@/components/async-component-child.vue&#39;))
    export default {
      name: &#39;async-components&#39;,
      components:{
        &#39;child&#39;: child
      }
    };
    </script>
2-2. Comparison of declaration methods

  • 2-2-1.The declaration of asynchronous components in Vue 2.x is A more advanced way of declaring. As follows:

  • const asyncPageWithOptions  = {
      component: () => import(&#39;./views/home.vue&#39;),
      delay: 200,
      timeout: 3000,
      error: ErrorComponent,
      loading: LoadingComponent
    }
So, the following asynchronous component declaration:

const asyncPage = () => import(&#39;./views/home.vue&#39;)

is equivalent to:

const asyncPageWithOptions  = {
  component: () => import(&#39;./views/home.vue&#39;)
}

  • 2-2 -2. Asynchronous components can also be declared like this in Vue 3.x. Only the component needs to be changed to loader. As follows:

  • const asyncPageWithOptions  = defineAsyncComponent({
      loader: () => import(&#39;./views/home.vue&#39;),
      delay: 200,
      timeout: 3000,
      error: ErrorComponent,
      loading: LoadingComponent
    })
2-3. Asynchronous component loading function returns comparison

  • 2-3-1. Received in Vue 2.x resolve and reject:

  • // 2.x version
    const oldAsyncComponent = (resolve, reject) => {
      /* ... */
    }
  • 2-3-2. In Vue 3.x always returns Promise:

  • // 3.x version
    const asyncComponent = defineAsyncComponent(
      () => new Promise((resolve, reject) => {
          /* ... */
      })
    )
Vue 3.x's asynchronous component loading function will no longer receive resolve and reject, and must always return Promise. In other words, in Vue 3.x, it is no longer supported to receive resolve callbacks through factory functions to define asynchronous components.

// 在 Vue 3.x 中不适用
export default {
  components: {
    asyncPage: resolve => require([&#39;@/components/list.vue&#39;], resolve)
  },
}

3. Vue3 practice

Tips: If you use the Vite tool to build the project, use import to do routing lazy loading during local development. It can be loaded normally, but a warning will be reported; package it to production. The environment will report an error and the page will not be displayed normally. You can use the following two methods to achieve this.

3-1. Routing lazy loading implementation

  • 3-1-1.defineAsyncComponent method

  • // router/index.js
    import { defineAsyncComponent } from &#39;vue&#39;
    const _import = (path) => defineAsyncComponent(() => import(`../views/${path}.vue`));
    const routes = [
      {
        path: &#39;/async-component&#39;,
        name: &#39;asyncComponent&#39;,
        component: _import(&#39;home&#39;),
      }
    ];
  • 3-1-2.import.meta.glob method

  • // 1.上面的方法相当于一次性加载了 views 目录下的所有.vue文件,返回一个对象
    const modules = import.meta.glob(&#39;../views/*/*.vue&#39;);
    const modules ={
        "../views/about/index.vue": () => import("./src/views/about/index.vue")
    }
    // 2.动态导入的时候直接,引用
    const router = createRouter({
      history: createWebHistory(),
      routes: [
        // ...
        {
          path: &#39;xxxx&#39;,
          name: &#39;xxxxx&#39;,
          // 原来的方式,这个在开发中可行,但是生产中不行
          // component: () => import(`../views${menu.file}`),
          // 改成下面这样
          component: modules[`../views${filename}`]
        }
        // ...          
      ],
    })
3-2.Asynchronous component implementation

<template>
  <div>
    <h2 id="Async-nbsp-Components">Async Components</h2>
    <p>异步组件测试</p>
    <child></child>
  </div>
</template>
<script>
import { defineAsyncComponent } from &#39;vue&#39;
const child = defineAsyncComponent(() => import(&#39;@/components/async-component-child.vue&#39;))
export default {
  name: &#39;async-components&#39;,
  components:{
    &#39;child&#39;: child
  }
};
</script>

The above is the detailed content of How to apply lazy loading of vue3 vite asynchronous components and routing. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
Why Does Vue.js Use a Virtual DOM Instead of Direct DOM Manipulation?Why Does Vue.js Use a Virtual DOM Instead of Direct DOM Manipulation?May 16, 2025 am 12:05 AM

Vue.js uses virtual DOM instead of directly operating DOM, in order to improve performance and development efficiency. 1) Virtual DOM is calculated through diff algorithm to minimize DOM operations and improve performance. 2) Simplify development, developers do not need to deal with DOM complexity. 3) Component reuse and combination are more efficient. The working principle of virtual DOM is to generate a comparison between the new tree and the old tree, update only the difference part, and reduce the number of DOM operations.

What Happens When the Vue.js Virtual DOM Detects a Change?What Happens When the Vue.js Virtual DOM Detects a Change?May 14, 2025 am 12:12 AM

WhentheVue.jsVirtualDOMdetectsachange,itupdatestheVirtualDOM,diffsit,andappliesminimalchangestotherealDOM.ThisprocessensureshighperformancebyavoidingunnecessaryDOMmanipulations.

How Accurate Is It to Think of Vue.js's Virtual DOM as a Mirror of the Real DOM?How Accurate Is It to Think of Vue.js's Virtual DOM as a Mirror of the Real DOM?May 13, 2025 pm 04:05 PM

Vue.js' VirtualDOM is both a mirror of the real DOM, and not exactly. 1. Create and update: Vue.js creates a VirtualDOM tree based on component definitions, and updates VirtualDOM first when the state changes. 2. Differences and patching: Comparison of old and new VirtualDOMs through diff operations, and apply only the minimum changes to the real DOM. 3. Efficiency: VirtualDOM allows batch updates, reduces direct DOM operations, and optimizes the rendering process. VirtualDOM is a strategic tool for Vue.js to optimize UI updates.

Vue.js vs. React: Scalability and MaintainabilityVue.js vs. React: Scalability and MaintainabilityMay 10, 2025 am 12:24 AM

Vue.js and React each have their own advantages in scalability and maintainability. 1) Vue.js is easy to use and is suitable for small projects. The Composition API improves the maintainability of large projects. 2) React is suitable for large and complex projects, with Hooks and virtual DOM improving performance and maintainability, but the learning curve is steeper.

The Future of Vue.js and React: Trends and PredictionsThe Future of Vue.js and React: Trends and PredictionsMay 09, 2025 am 12:12 AM

The future trends and forecasts of Vue.js and React are: 1) Vue.js will be widely used in enterprise-level applications and have made breakthroughs in server-side rendering and static site generation; 2) React will innovate in server components and data acquisition, and further optimize the concurrency model.

Netflix's Frontend: A Deep Dive into Its Technology StackNetflix's Frontend: A Deep Dive into Its Technology StackMay 08, 2025 am 12:11 AM

Netflix's front-end technology stack is mainly based on React and Redux. 1.React is used to build high-performance single-page applications, and improves code reusability and maintenance through component development. 2. Redux is used for state management to ensure that state changes are predictable and traceable. 3. The toolchain includes Webpack, Babel, Jest and Enzyme to ensure code quality and performance. 4. Performance optimization is achieved through code segmentation, lazy loading and server-side rendering to improve user experience.

Vue.js and the Frontend: Building Interactive User InterfacesVue.js and the Frontend: Building Interactive User InterfacesMay 06, 2025 am 12:02 AM

Vue.js is a progressive framework suitable for building highly interactive user interfaces. Its core functions include responsive systems, component development and routing management. 1) The responsive system realizes data monitoring through Object.defineProperty or Proxy, and automatically updates the interface. 2) Component development allows the interface to be split into reusable modules. 3) VueRouter supports single-page applications to improve user experience.

What are the disadvantages of VueJs?What are the disadvantages of VueJs?May 05, 2025 am 12:06 AM

The main disadvantages of Vue.js include: 1. The ecosystem is relatively new, and third-party libraries and tools are not as rich as other frameworks; 2. The learning curve becomes steep in complex functions; 3. Community support and resources are not as extensive as React and Angular; 4. Performance problems may be encountered in large applications; 5. Version upgrades and compatibility challenges are greater.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment