Async Components

Overview

Here is a high level overview of what has changed:

  • New defineAsyncComponent helper method that explicitly defines async components
  • component option renamed to loader
  • Loader function does not inherently receive resolve and reject arguments and must return a Promise

For a more in-depth explanation, read on!

Introduction

Previously, async components were created by simply defining a component as a function that returned a promise, such as:

  1. const asyncPage = () => import('./NextPage.vue')

Or, for the more advanced component syntax with options:

  1. const asyncPage = {
  2. component: () => import('./NextPage.vue'),
  3. delay: 200,
  4. timeout: 3000,
  5. error: ErrorComponent,
  6. loading: LoadingComponent
  7. }

3.x Syntax

Now, in Vue 3, since functional components are defined as pure functions, async components definitions need to be explicitly defined by wrapping it in a new defineAsyncComponent helper:

  1. import { defineAsyncComponent } from 'vue'
  2. import ErrorComponent from './components/ErrorComponent.vue'
  3. import LoadingComponent from './components/LoadingComponent.vue'
  4. // Async component without options
  5. const asyncPage = defineAsyncComponent(() => import('./NextPage.vue'))
  6. // Async component with options
  7. const asyncPageWithOptions = defineAsyncComponent({
  8. loader: () => import('./NextPage.vue'),
  9. delay: 200,
  10. timeout: 3000,
  11. errorComponent: ErrorComponent,
  12. loadingComponent: LoadingComponent
  13. })

Another change that has been made from 2.x is that the component option is now renamed to loader in order to accurately communicate that a component definition cannot be provided directly.

  1. import { defineAsyncComponent } from 'vue'
  2. const asyncPageWithOptions = defineAsyncComponent({
  3. loader: () => import('./NextPage.vue'),
  4. delay: 200,
  5. timeout: 3000,
  6. error: ErrorComponent,
  7. loading: LoadingComponent
  8. })

In addition, unlike 2.x, the loader function no longer receives the resolve and reject arguments and must always return a Promise.

  1. // 2.x version
  2. const oldAsyncComponent = (resolve, reject) => {
  3. /* ... */
  4. }
  5. // 3.x version
  6. const asyncComponent = defineAsyncComponent(
  7. () =>
  8. new Promise((resolve, reject) => {
  9. /* ... */
  10. })
  11. )

For more information on the usage of async components, see: