Skip to content

What Is an Async Component in Vue?

In Vue, an "async component" is a component that is loaded asynchronously. It is used when a component does not need to be loaded as soon as the application starts or the page opens, and it is especially useful for improving performance in large applications.

In Vue 3, async components are defined with the defineAsyncComponent function and a dynamic import(), so the component's code is fetched only when it is needed. Here is an example:

JavaScriptCode fragment
// AsyncComponent.js
import { defineAsyncComponent } from 'vue';

const AsyncComponent = defineAsyncComponent(() => import('./MyComponent.vue'));

export default AsyncComponent;

Here an async component called AsyncComponent is created. The ./MyComponent.vue file inside import() is the component to load; it is downloaded when the user opens the page or when a particular event happens.

You use the async component inside another component like this:

VueCode fragment
<!-- App.vue -->
<template>
  <div>
    <AsyncComponent />
  </div>
</template>

<script>
import AsyncComponent from './AsyncComponent.js';

export default {
  components: {
    AsyncComponent,
  },
};
</script>

AsyncComponent is registered in the components option like any other component. Vue downloads MyComponent.vue as a separate chunk the first time the component is shown, which keeps the initial page load smaller.

Note: In Vue 2 it was enough to pass a () => import(...) function as a component. In Vue 3, components must use defineAsyncComponent; a plain () => import(...) is only valid in Vue Router route definitions. defineAsyncComponent also lets you set components to show while loading and on error (loadingComponent, errorComponent).

Have a question about this article? Write to me