Episode 28 of 44

Dynamic Components

Switch between components dynamically using the component tag and keep-alive to preserve state across switches.

Dynamic Components

Sometimes you need to swap between components dynamically — like tabs where each tab shows a different component. Vue's <component> element and :is attribute make this easy.

The component Tag

<component :is="currentComponent"></component>

data() {
    return {
        currentComponent: 'form-one'
    };
}

The :is attribute takes a component name (string) or a component object. When the value changes, Vue swaps to the new component.

Switching Components

<template>
    <div>
        <button @click="currentComponent = 'form-one'">Form 1</button>
        <button @click="currentComponent = 'form-two'">Form 2</button>
        <component :is="currentComponent"></component>
    </div>
</template>

Preserving State with keep-alive

<keep-alive>
    <component :is="currentComponent"></component>
</keep-alive>

Without <keep-alive>, switching destroys the old component and creates a new one — losing any data the user entered. With <keep-alive>, components are cached and their state is preserved.

keep-alive Lifecycle Hooks

HookWhen It Runs
activatedWhen a kept-alive component is shown again
deactivatedWhen a kept-alive component is hidden

Key Takeaways

  • <component :is="name"> renders the component matching the name dynamically
  • Wrap in <keep-alive> to cache components and preserve their state
  • activated and deactivated hooks run when kept-alive components are shown/hidden