TExcelTAD
Home › Vue › Vue Dynamic Components

Vue Dynamic Components

Sometimes which component to show depends on data: the active tab, the current step of a wizard, the type of a dashboard widget. Instead of a long v-if / v-else-if chain, Vue offers the special <component> element with an :is attribute. It renders whatever component :is points to — and switches when the value changes.

html
<component :is="currentTab"></component>

:is can be:

  • the name of a registered component (a string such as 'tab-home'),
  • a component object itself (common with <script setup> imports),
  • or the name of a plain HTML element ('button', 'h2'…).

Tabs with <component :is>

html · try it yourself
<style>
  .tabs button { border: none; padding: 6px 12px; background: #eee; cursor: pointer; }
  .tabs button.active { background: #42b883; color: white; }
  .panel { border: 1px solid #ddd; padding: 12px; min-height: 70px; }
</style>

<div id="app">
  <div class="tabs">
    <button v-for="t in tabs" :key="t.id" :class="{ active: current === t.id }" @click="current = t.id">
      {{ t.label }}
    </button>
  </div>
  <div class="panel">
    <component :is="current"></component>
  </div>
</div>

<script type="module">
  import { createApp } from 'vue';

  const app = createApp({
    data: () => ({
      current: 'tab-home',
      tabs: [
        { id: 'tab-home', label: 'Home' },
        { id: 'tab-posts', label: 'Posts' },
        { id: 'tab-settings', label: 'Settings' }
      ]
    })
  });

  app.component('tab-home', { template: `<p>🏠 Welcome home!</p>` });
  app.component('tab-posts', {
    data: () => ({ posts: ['Learning Vue', 'Dynamic components'] }),
    template: `<ul><li v-for="p in posts" :key="p">{{ p }}</li></ul>`
  });
  app.component('tab-settings', {
    data: () => ({ dark: false }),
    template: `<label><input type="checkbox" v-model="dark"> Dark mode ({{ dark ? 'on' : 'off' }})</label>`
  });

  app.mount('#app');
</script>

Tick the "Dark mode" checkbox, switch to another tab and back: the checkbox is unticked again. When you switch away, the old component is unmounted and its state is lost.

Keeping state with <KeepAlive>

Wrap the dynamic component in <KeepAlive> (in in-DOM templates: <keep-alive>) and Vue caches inactive components instead of destroying them.

html · try it yourself
<div id="app">
  <button v-for="s in steps" :key="s" @click="current = s" :disabled="current === s">{{ s }}</button>
  <label><input type="checkbox" v-model="keep"> use &lt;keep-alive&gt;</label>
  <hr>
  <keep-alive v-if="keep">
    <component :is="current"></component>
  </keep-alive>
  <component v-else :is="current"></component>
</div>

<script type="module">
  import { createApp } from 'vue';

  const app = createApp({
    data: () => ({ steps: ['step-name', 'step-email'], current: 'step-name', keep: true })
  });

  const logLifecycle = (label) => ({
    mounted() { console.log(label, 'mounted'); },
    unmounted() { console.log(label, 'unmounted'); },
    activated() { console.log(label, 'activated (from cache)'); },
    deactivated() { console.log(label, 'deactivated (kept in cache)'); }
  });

  app.component('step-name', {
    ...logLifecycle('step-name'),
    data: () => ({ name: '' }),
    template: `<label>Name: <input v-model="name" placeholder="type, then switch"></label>`
  });
  app.component('step-email', {
    ...logLifecycle('step-email'),
    data: () => ({ email: '' }),
    template: `<label>Email: <input v-model="email" type="email"></label>`
  });

  app.mount('#app');
</script>

Type a name, switch to the email step and back — with keep-alive the name is still there. Watch the log: cached components receive deactivated / activated instead of unmounted / mounted.

<KeepAlive> prop Meaning
include="a,b" Only cache components whose name matches (string, RegExp or array)
exclude="c" Never cache these
:max="10" Cache at most 10 instances; the least recently used is dropped

Passing props and listeners

Props and events on <component> are forwarded to whatever component is rendered:

html
<component :is="widgetType" :data="widgetData" @refresh="reload"></component>

Using component objects

When components are plain objects (or imported from .vue files), pass the object itself. Use markRaw when storing component objects inside reactive state, so Vue doesn't make them reactive.

html · try it yourself
<div id="app">
  <select v-model="shape">
    <option value="circle">Circle</option>
    <option value="square">Square</option>
  </select>
  <component :is="shapes[shape]" :size="60"></component>
</div>

<script type="module">
  import { createApp, ref, markRaw } from 'vue';

  const CircleShape = {
    props: ['size'],
    template: `<div :style="{ width: size + 'px', height: size + 'px', borderRadius: '50%', background: '#42b883' }"></div>`
  };
  const SquareShape = {
    props: ['size'],
    template: `<div :style="{ width: size + 'px', height: size + 'px', background: '#3b82f6' }"></div>`
  };

  createApp({
    setup() {
      const shape = ref('circle');
      const shapes = markRaw({ circle: CircleShape, square: SquareShape });
      return { shape, shapes };
    }
  }).mount('#app');
</script>

Async components

Large components can be loaded on demand with defineAsyncComponent. Vue calls the loader the first time the component is rendered. In a Vite project the loader is usually a dynamic import, which becomes a separate file in the build:

js
import { defineAsyncComponent } from 'vue';

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

// with loading and error states
const Chart = defineAsyncComponent({
  loader: () => import('./BigChart.vue'),
  loadingComponent: LoadingSpinner,
  errorComponent: LoadError,
  delay: 200,       // show the spinner only if loading takes > 200 ms
  timeout: 5000
});

Tip: Combine async components with <component :is> for things like dashboards where each widget type lives in its own file and is only downloaded when used.

Note: In in-DOM templates, <component>, <keep-alive>, <transition> and <teleport> are written in lowercase/kebab-case. In SFCs you will usually see <KeepAlive>, <Transition> and <Teleport>.

Test yourself

Which element renders a component chosen at runtime?

  1. <slot :is="x">
  2. <component :is="x">
  3. <dynamic :name="x">
  4. <template v-is="x">

What happens to a dynamic component's state when you switch away, without KeepAlive?

  1. It is cached
  2. It is unmounted and its state is lost
  3. It is hidden with display: none
  4. It moves to the end of the page

Which lifecycle hook runs when a cached component is shown again by KeepAlive?

  1. mounted
  2. created
  3. activated
  4. updated