Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ

Vue 3 Asynchronous Components Redefining

Jun 01, 2021 Article blog

Table of contents

Let's first look at the changes to asynchronous components:

  • A new method, defineAsyncComponent is used to explicitly define asynchronous components

  • component option changes its name: loader

  • Loader function no longer resolve and reject as arguments, and must return a Promise

Once an asynchronous component

In Vue 2.x it is convenient to define an asynchronous component:

const asyncPage = () => import('./HugePageComponent.vue');

If you need some advanced usage (I bet five cents you don't know this usage):

import { ErrorComponent, LoadingComponent } from 'xxx'; const asyncPage = { component: () => import('./HugePageComponent'), delay: 1000, timeout: 3000, error: ErrorComponent, loading: LoadingComponent, }

Upcoming Vue 3 asynchronous components

Because functional components are defined by normal functions in Vue 3 asynchronous components need to be explicitly defined through defineAsyncComponent

import { defineAsyncComponent } from 'vue'; import { ErrorComponent, LoadingComponent } from 'xxx';

// 常规用法
const asyncPage = defineAsyncComponent(() => import('./HugePageComponent'));

// 高级用法
const asyncPageWithOptions = defineAsyncComponent({
  // 这里之前是 component,现在改叫 loader 了 
  loader: () => import('./HugePageComponent'),
  delay: 1000,
  timeout: 3000,
  errorComponent: ErrorComponent,
  loadingComponent: LoadingComponent,

In addition, unlike Vue 2.x loader function no longer resolve and reject as the default parameters, and must return a Promise

2.x version const oldAsyncComponent s (resolve, reject) s/> / ... / }

// 3.x 版本
const newAsyncComponent = defineAsyncComponent(
 () => {
    return new Promise((resolve, reject) => {
      /* ... */

These are Vue 3 changes to asynchronous components, and students interested in Vue can take a look at the tutorial

Vue 1 tutorial:

Vue 2 tutorial:

Vue 2.x Microsyscope: