Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 87 ยท Components

Dynamic and Async Components

Switch components at runtime with component :is, keep their state with KeepAlive, and load heavy ones lazily with defineAsyncComponent, including loading and error states.

Most templates name their components directly: <UserCard />. But some screens need to decide which component to show while the app runs. A tab bar shows one of several panels, a dashboard renders widgets chosen by the user, a form wizard moves through steps. And some components are large and rarely needed, so loading their code only when they are first displayed makes the app start faster.

Vue covers both situations. The special element <component :is="..."> renders whichever component you point it at. The built-in <KeepAlive> remembers the state of components you switch away from. And defineAsyncComponent() wraps a component that is loaded on demand, with optional loading and error states. This lesson builds on Components Basics and Slots, and prepares the lazy-loading topics in Large Lists and Lazy Loading.

The examples run in a sandboxed preview with no build step, so every component is a plain object with a template string. Vue 3.5.13 (the full browser build with the template compiler) comes from jsDelivr. Real lazy loading uses import('./File.vue'), which needs a bundler. It is shown read-only, and the live example simulates a slow download with a timer.

Switching with component :is

<component :is="X" /> is a placeholder that turns into the component X. The value of :is can be a registered component name (a string) or the component object itself. When the value changes, Vue unmounts the old component and mounts the new one.

flowchart LR
  S["state: current = 'CounterTab'"] --> C["&lt;component :is='current' /&gt;"]
  C -->|"current changes"| U["old component unmounted"]
  U --> M["new component mounted"]

Changing the is value swaps the component that occupies this spot.

Two points that surprise newcomers. First, a string works only if the component is registered (locally in components, or globally). Second, if you keep component objects in reactive state, Vue warns that it is making a component reactive; use markRaw() or shallowRef() for such values (How Reactivity Works explains why). Storing names or keys is simpler and also serialisable.

Keeping state with KeepAlive

By default, switching away destroys a component and its state. Type something into a form tab, click another tab and come back: the text is gone, because a new instance was created. Wrap the dynamic component in <KeepAlive> and Vue caches the inactive instance instead of destroying it. The state (and the DOM) is restored when you return.

A cached component gets two extra lifecycle hooks: onActivated (it became visible, also on first mount) and onDeactivated (it was cached). The onMounted hook runs only once. See Lifecycle Hooks for the full picture, and Teleport and KeepAlive for include, exclude and max.

The example below has two tabs: a counter and a text field. A checkbox switches KeepAlive on and off, and a log lists the lifecycle events. Try this: type "hi", increment the counter, switch tabs and come back, once with KeepAlive off and once with it on.

component :is with and without KeepAlive

With KeepAlive off, each tab switch logs "mounted" and "unmounted" and the state starts from zero. With it on, you will see "deactivated" and "activated" instead, and the counter keeps its value. (Flipping the checkbox itself swaps the whole wrapper, which recreates the current tab once.)

Async components

A async component is a component that is not available yet when the app starts. You describe how to load it, and Vue loads it the first time it is rendered. With a bundler, import() makes the loaded file a separate chunk, so the first visit downloads less code.

HTML
<!-- Read-only: needs a bundler such as Vite -->
<script setup>
import { defineAsyncComponent } from 'vue'

const HeavyChart = defineAsyncComponent(() => import('./HeavyChart.vue'))
</script>

<template>
  <HeavyChart v-if="showChart" />
</template>

defineAsyncComponent takes a loader: a function that returns a promise of a component. It also accepts an options object for the states around the load:

Option Meaning
loader Function returning a promise of the component
loadingComponent Shown while loading
delay Milliseconds to wait before showing the loading component (default 200), which avoids a flash for fast loads
errorComponent Shown if the promise rejects or the timeout passes
timeout If loading takes longer, the error component is shown (default: never)
onError Hook to retry or fail, see below
stateDiagram-v2
  [*] --> Idle
  Idle --> Loading: component rendered
  Loading --> Ready: promise resolves
  Loading --> Failed: rejects or timeout
  Ready --> [*]
  Failed --> Loading: rendered again (new attempt)

An async component moves from loading to ready or failed. A failed load is tried again the next time it is rendered.

In the next example the loader is a simulated download: a promise that resolves after 600 ms (a stand-in for import()). The counter shows how often the loader actually runs. Notice that after a successful load the result is kept, so showing the widget again is instant and the loader does not run again, while the broken widget is attempted anew every time. (The failing loader also reports its error in the browser console, as Vue treats an unhandled loading error as a problem you should know about.)

Loading and error states for async components

Retrying with onError

For flaky networks you can retry automatically. The onError option receives the error, a retry function, a fail function and the attempt count:

JavaScript
// Read-only snippet
const Reports = defineAsyncComponent({
  loader: () => import('./Reports.vue'),
  onError(error, retry, fail, attempts) {
    if (attempts <= 3) {
      retry()
    } else {
      fail()
    }
  }
})

Where lazy loading pays off

Do not make every component async: each chunk costs an extra request, and tiny components are cheaper in the main bundle. Measure first (Performance Basics).

Vue also offers an experimental <Suspense> component that coordinates several async dependencies in one fallback. It is still experimental and its API may change, so this tutorial does not rely on it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What can the is attribute of <component> be?

    :is accepts a registered name string (resolved against registered components) or the component definition itself.
  2. 2. You switch away from a form tab and come back, and the typed text is gone. How do you keep it?

    KeepAlive caches the inactive instance, so its state is restored when it becomes active again. A key would force recreation, the opposite of what you want.
  3. 3. Which hook runs each time a KeepAlive-cached component becomes visible again?

    onMounted only runs once for a cached component. onActivated runs on first mount and on every re-activation, and onDeactivated runs when it is cached.
  4. 4. What does the delay option of defineAsyncComponent control?

    The download starts immediately. delay only postpones the loading indicator (200 ms by default), so quick loads show no flicker.
  5. 5. After an async component loaded successfully, you hide it and show it again. What happens?

    Vue keeps the resolved component. Only a failed load is tried again the next time the component is rendered.

Summary

  • <component :is="..."> renders a component chosen at runtime, by registered name or by component object.
  • Switching destroys the old instance; wrap it in <KeepAlive> to cache its state, and use onActivated / onDeactivated for visibility hooks.
  • defineAsyncComponent(loader) loads a component on first render; import() makes each one a separate chunk.
  • Options loadingComponent, delay, errorComponent, timeout and onError handle the states around loading.
  • A successful load is cached; a failed one is retried the next time the component renders.
  • Lazy-load routes and heavy, rarely used UI, and measure before splitting everything.

Next, learn how to reach elements and child components from code in Template Refs and Exposing Methods.