JAVASCRIPT

Dynamic Component Rendering with Vue 3 `component` element

Learn to dynamically switch between Vue 3 components using the `<component :is='...' />` element, ideal for tabbed interfaces or conditional rendering scenarios.

<template>
  <div>
    <button @click="activeComponent = 'HomeComponent'">Show Home</button>
    <button @click="activeComponent = 'AboutComponent'">Show About</button>

    <hr />

    <component :is="activeComponent"></component>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import HomeComponent from './HomeComponent.vue';
import AboutComponent from './AboutComponent.vue';

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

<!-- HomeComponent.vue -->
<template>
  <div>
    <h2>Home Component</h2>
    <p>Welcome to the home page!</p>
  </div>
</template>

<!-- AboutComponent.vue -->
<template>
  <div>
    <h2>About Component</h2>
    <p>Learn more about us here.</p>
  </div>
</template>
How it works: This snippet demonstrates how to render components dynamically in Vue 3 using the special `<component>` element and its `:is` attribute. By binding `:is` to a reactive variable (e.g., `activeComponent`), you can switch between different imported components based on user interaction or application state. This pattern is incredibly useful for building tabbed interfaces, wizards, or highly configurable dashboards where the displayed content changes frequently.

Need help integrating this into your project?

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

Hire DigitalCodeLabs