Table of Contents
1. Preface
1-1. Three changes:
1-2. The reason for introducing the auxiliary function defineAsyncComponent:
2. Comparison of Vue 2.x and Vue 3.x definitions
2-1. Comparison of asynchronous component/routing definitions
Home Web Front-end Vue.js How to apply lazy loading of vue3 vite asynchronous components and routing

How to apply lazy loading of vue3 vite asynchronous components and routing

May 18, 2023 pm 04:52 PM
vue3 vite

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')
    Copy after login
    Copy after login
  • 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>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>
    Copy after login
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
    }
    Copy after login
So, the following asynchronous component declaration:

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

is equivalent to:

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

  • 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
    })
    Copy after login
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) => {
      /* ... */
    }
    Copy after login
  • 2-3-2. In Vue 3.x always returns Promise:

  • // 3.x version
    const asyncComponent = defineAsyncComponent(
      () => new Promise((resolve, reject) => {
          /* ... */
      })
    )
    Copy after login
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)
  },
}
Copy after login

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;),
      }
    ];
    Copy after login
  • 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}`]
        }
        // ...          
      ],
    })
    Copy after login
3-2.Asynchronous component implementation

<template>
  <div>
    <h2>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>
Copy after login

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Vue3+TS+Vite development skills: how to optimize SEO Vue3+TS+Vite development skills: how to optimize SEO Sep 10, 2023 pm 07:33 PM

Vue3+TS+Vite development skills: How to perform SEO optimization SEO (SearchEngineOptimization) refers to optimizing the structure, content and keywords of the website to rank it higher in search engines, thereby increasing the website's traffic and exposure. . In the development of modern front-end technologies such as Vue3+TS+Vite, how to optimize SEO is a very important issue. This article will introduce some Vue3+TS+Vite development techniques and methods to help

vue3+vite: How to solve the error when using require to dynamically import images in src vue3+vite: How to solve the error when using require to dynamically import images in src May 21, 2023 pm 03:16 PM

vue3+vite:src uses require to dynamically import images and error reports and solutions. vue3+vite dynamically imports multiple images. If vue3 is using typescript development, require will introduce image errors. requireisnotdefined cannot be used like vue2 such as imgUrl:require(' .../assets/test.png') is imported because typescript does not support require, so import is used. Here is how to solve it: use awaitimport

How to refresh partial content of the page in Vue3 How to refresh partial content of the page in Vue3 May 26, 2023 pm 05:31 PM

To achieve partial refresh of the page, we only need to implement the re-rendering of the local component (dom). In Vue, the easiest way to achieve this effect is to use the v-if directive. In Vue2, in addition to using the v-if instruction to re-render the local dom, we can also create a new blank component. When we need to refresh the local page, jump to this blank component page, and then jump back in the beforeRouteEnter guard in the blank component. original page. As shown in the figure below, how to click the refresh button in Vue3.X to reload the DOM within the red box and display the corresponding loading status. Since the guard in the component in the scriptsetup syntax in Vue3.X only has o

Vue3+TS+Vite development skills: how to carry out front-end security protection Vue3+TS+Vite development skills: how to carry out front-end security protection Sep 09, 2023 pm 04:19 PM

Vue3+TS+Vite development skills: How to carry out front-end security protection. With the continuous development of front-end technology, more and more companies and individuals are beginning to use Vue3+TS+Vite for front-end development. However, the security risks that come with it have also attracted people's attention. In this article, we will discuss some common front-end security issues and share some tips on how to protect front-end security during the development process of Vue3+TS+Vite. Input validation User input is often one of the main sources of front-end security vulnerabilities. exist

Vue3+TS+Vite development skills: how to optimize cross-domain requests and network requests Vue3+TS+Vite development skills: how to optimize cross-domain requests and network requests Sep 09, 2023 pm 04:40 PM

Vue3+TS+Vite development skills: How to optimize cross-domain requests and network requests Introduction: In front-end development, network requests are a very common operation. How to optimize network requests to improve page loading speed and user experience is one of the issues that our developers need to think about. At the same time, for some scenarios that require sending requests to different domain names, we need to solve cross-domain issues. This article will introduce how to make cross-domain requests and optimization techniques for network requests in the Vue3+TS+Vite development environment. 1. Cross-domain request solution

How Vue3 parses markdown and implements code highlighting How Vue3 parses markdown and implements code highlighting May 20, 2023 pm 04:16 PM

Vue implements the blog front-end and needs to implement markdown parsing. If there is code, it needs to implement code highlighting. There are many markdown parsing libraries for Vue, such as markdown-it, vue-markdown-loader, marked, vue-markdown, etc. These libraries are all very similar. Marked is used here, and highlight.js is used as the code highlighting library. The specific implementation steps are as follows: 1. Install dependent libraries. Open the command window under the vue project and enter the following command npminstallmarked-save//marked to convert markdown into htmlnpmins

Vue3+TS+Vite development skills: how to encrypt and store data Vue3+TS+Vite development skills: how to encrypt and store data Sep 10, 2023 pm 04:51 PM

Vue3+TS+Vite development tips: How to encrypt and store data. With the rapid development of Internet technology, data security and privacy protection are becoming more and more important. In the Vue3+TS+Vite development environment, how to encrypt and store data is a problem that every developer needs to face. This article will introduce some common data encryption and storage techniques to help developers improve application security and user experience. 1. Data Encryption Front-end Data Encryption Front-end encryption is an important part of protecting data security. Commonly used

How to use vue3+ts+axios+pinia to achieve senseless refresh How to use vue3+ts+axios+pinia to achieve senseless refresh May 25, 2023 pm 03:37 PM

vue3+ts+axios+pinia realizes senseless refresh 1. First download aiXos and pinianpmipinia in the project--savenpminstallaxios--save2. Encapsulate axios request-----Download js-cookienpmiJS-cookie-s//Introduce aixosimporttype{AxiosRequestConfig ,AxiosResponse}from"axios";importaxiosfrom'axios';import{ElMess

See all articles