JAVASCRIPT

Vue 3 Dynamic Components with KeepAlive for Tabbed Interfaces

Implement dynamic component rendering in Vue 3 using `<component :is='...' />` and `<KeepAlive>` to maintain component state and improve performance in tabbed UIs.

// src/components/TabA.vue
<template>
  <div class="p-4 bg-white rounded shadow">
    <h2 class="text-xl font-semibold mb-2">Tab A Content</h2>
    <p>This is the content for Tab A.</p>
    <input type="text" placeholder="Enter something..." class="mt-2 p-2 border rounded w-full">
    <p class="mt-2 text-sm text-gray-500">Type here, then switch tabs and come back. Your input will be preserved!</p>
  </div>
</template>

// src/components/TabB.vue
<template>
  <div class="p-4 bg-white rounded shadow">
    <h2 class="text-xl font-semibold mb-2">Tab B Content</h2>
    <p>This is the content for Tab B.</p>
    <textarea placeholder="Enter a message..." rows="3" class="mt-2 p-2 border rounded w-full"></textarea>
    <p class="mt-2 text-sm text-gray-500">The state of this textarea will also be preserved.</p>
  </div>
</template>

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

const currentTab = ref('TabA');

const tabs = {
  TabA,
  TabB
};
</script>

<template>
  <div class="p-8 bg-gray-100 min-h-screen">
    <h1 class="text-3xl font-bold mb-6">Dynamic Tabs with KeepAlive</h1>

    <div class="mb-4">
      <button
        @click="currentTab = 'TabA'"
        :class="{'bg-blue-600 text-white': currentTab === 'TabA', 'bg-blue-400 text-gray-100': currentTab !== 'TabA'}"
        class="px-4 py-2 rounded-l-md hover:bg-blue-500 transition-colors"
      >
        Tab A
      </button>
      <button
        @click="currentTab = 'TabB'"
        :class="{'bg-blue-600 text-white': currentTab === 'TabB', 'bg-blue-400 text-gray-100': currentTab !== 'TabB'}"
        class="px-4 py-2 rounded-r-md hover:bg-blue-500 transition-colors"
      >
        Tab B
      </button>
    </div>

    <div class="border border-gray-300 rounded-lg p-6 bg-gray-50">
      <KeepAlive>
        <component :is="tabs[currentTab]"></component>
      </KeepAlive>
    </div>
  </div>
</template>
How it works: This snippet demonstrates how to use Vue 3's `<component :is='...' />` to dynamically render components based on a reactive state (`currentTab`). The crucial part is wrapping the dynamic component with `<KeepAlive>`. This built-in component ensures that inactive dynamic components are not unmounted, but instead cached. When you switch back to a previously visited tab, its state (e.g., input field values) is preserved, significantly improving user experience and performance for complex interfaces.

Need help integrating this into your project?

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

Hire DigitalCodeLabs