JAVASCRIPT

Build Dynamic Tabbed Interfaces with Vue 3 Components

Learn how to dynamically render different components based on selected tabs or conditions using Vue 3's built-in `<component :is="...">` pattern for flexible UIs.

// src/components/TabA.vue
<template>
  <div class="tab-content">
    <h2>Content for Tab A</h2>
    <p>This is the first tab's information.</p>
  </div>
</template>

// src/components/TabB.vue
<template>
  <div class="tab-content">
    <h2>Content for Tab B</h2>
    <p>This is the second tab's information.</p>
  </div>
</template>

// src/App.vue
<template>
  <div class="container">
    <nav class="tabs">
      <button @click="currentTab = 'TabA'" :class="{ active: currentTab === 'TabA' }">Tab A</button>
      <button @click="currentTab = 'TabB'" :class="{ active: currentTab === 'TabB' }">Tab B</button>
    </nav>

    <div class="tab-wrapper">
      <component :is="currentTabComponent"></component>
    </div>
  </div>
</template>

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

const currentTab = ref('TabA'); // Initial tab

const tabs = {
  TabA,
  TabB
};

const currentTabComponent = computed(() => tabs[currentTab.value]);
</script>

<style>
.tabs button {
  padding: 10px 15px;
  margin-right: 5px;
  border: 1px solid #ccc;
  background: #f0f0f0;
  cursor: pointer;
}
.tabs button.active {
  background: #007bff;
  color: white;
  border-color: #007bff;
}
.tab-wrapper {
  margin-top: 20px;
  padding: 20px;
  border: 1px solid #eee;
  border-radius: 5px;
}
</style>
How it works: This snippet demonstrates how to use Vue 3's dynamic components feature with the `<component :is="...">` syntax. It allows you to switch between different components dynamically based on a reactive value (`currentTab`). The `currentTabComponent` computed property resolves the actual component based on `currentTab`'s value, enabling the creation of flexible tabbed interfaces, wizards, or dynamic form sections easily.

Need help integrating this into your project?

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

Hire DigitalCodeLabs