JAVASCRIPT

Dynamically Render Components with Vue 3's `<component>` Tag

Learn how to use Vue 3's `<component>` tag with the `:is` prop to dynamically switch between different components based on data or user interaction, creating highly flexible UIs.

// App.vue
<template>
  <div>
    <button @click="currentTab = 'HomeTab'">Home</button>
    <button @click="currentTab = 'AboutTab'">About</button>
    <button @click="currentTab = 'ContactTab'">Contact</button>

    <div style="border: 1px solid #eee; padding: 20px; margin-top: 10px;">
      <component :is="currentTabComponent"></component>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import HomeTab from './components/HomeTab.vue';
import AboutTab from './components/AboutTab.vue';
import ContactTab from './components/ContactTab.vue';

const currentTab = ref('HomeTab');

const tabs = {
  HomeTab,
  AboutTab,
  ContactTab,
};

const currentTabComponent = computed(() => {
  return tabs[currentTab.value] || HomeTab; // Fallback to HomeTab
});
</script>

// components/HomeTab.vue
<template>
  <h3>Home Content</h3>
  <p>Welcome to the home page!</p>
</template>

// components/AboutTab.vue
<template>
  <h3>About Us</h3>
  <p>Learn more about our company.</p>
</template>

// components/ContactTab.vue
<template>
  <h3>Contact Information</h3>
  <p>Reach out to us!</p>
</template>
How it works: This pattern is crucial for building tabbed interfaces, wizards, or dashboards where the content changes dynamically. By binding the `:is` prop of the `<component>` tag to a computed property that returns a component definition, you can easily swap components at runtime. This allows for highly modular and adaptable user interfaces without complex conditional rendering logic.

Need help integrating this into your project?

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

Hire DigitalCodeLabs