Vue3 Fundamentals · Built-in Components

Load a component on demand

Loading components on demand with defineAsyncComponent

Load a component on demand

Some components are heavy, or rarely used. Shipping them in the first bundle makes the page slower for everyone. defineAsyncComponent lets you load a component only when it is needed.

You hand it a loader — a function that returns a promise of a component:

import { defineAsyncComponent } from 'vue';

const AsyncHello = defineAsyncComponent(() => Promise.resolve(Hello));

Vue calls the loader when the component first renders, waits for the promise, and shows the component once it resolves. Until then the slot is empty, unless you wrap it in <Suspense> or give the async component a loading component.

In a real app the loader is usually () => import('./Hello.vue'). The dynamic import lets the bundler split that component into its own chunk and fetch it on demand; here the loader resolves a component defined in the same file.

The file already defines a Hello component and renders it directly. Wrap it in defineAsyncComponent so it loads on demand. The Test checks the content is absent at first, then present once the loader resolves. The starter renders Hello synchronously, so the content is there immediately and the Test fails.

Challenge

The component loads up front instead of on demand. Wrap it: export an App component from App.vue whose template renders defineAsyncComponent(() => Promise.resolve(Hello)).

The Test checks the content is absent at first, then present once the loader resolves. The starter renders Hello directly, so the content is there immediately and the Test fails.

App.vue
<script setup>
import { h } from 'vue';

const Hello = {
  render: () => h('p', { 'data-test': 'async' }, 'Loaded on demand'),
};
</script>

<template>
  <Hello />
</template>

No test run yet

The Test is hidden. Run it to check the Challenge — you only see the result, never the test source.