JAVASCRIPT

Dynamic Components with `is` and `KeepAlive` for Tabbed Interface in Vue 3

Learn to create flexible user interfaces in Vue 3 using dynamic components with the `is` attribute, and `KeepAlive` to preserve component state when switching tabs.

// components/TabA.vue
<template>
  <div>
    <h2>Tab A Content</h2>
    <p>This is the content for Tab A.</p>
    <input type="text" placeholder="Enter something in Tab A" />
  </div>
</template>
<script setup></script>

// components/TabB.vue
<template>
  <div>
    <h2>Tab B Content</h2>
    <p>This is the content for Tab B.</p>
    <textarea placeholder="Enter something in Tab B"></textarea>
  </div>
</template>
<script setup></script>

// App.vue (example usage)
<template>
  <div>
    <button @click="activeComponent = 'TabA'">Show Tab A</button>
    <button @click="activeComponent = 'TabB'">Show Tab B</button>

    <div class="component-container">
      <keep-alive>
        <component :is="activeComponent" />
      </keep-alive>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import TabA from './components/TabA.vue';
import TabB from './components/TabB.vue';

const activeComponent = ref('TabA');
</script>

<style scoped>
.component-container {
  border: 1px solid #ccc;
  padding: 20px;
  margin-top: 20px;
  min-height: 150px;
}
</style>
How it works: This snippet demonstrates how to render dynamic components in Vue 3 using the `<component :is="activeComponent" />` syntax. The `activeComponent` ref determines which component (`TabA` or `TabB`) is currently rendered. Crucially, wrapping the dynamic component with `<KeepAlive>` ensures that when a component is switched out, its instance is cached instead of being unmounted. This preserves its state (e.g., input values), providing a smoother user experience, especially in tabbed interfaces.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs