JAVASCRIPT
Dynamically Rendering Vue 3 Components with <component :is>
Discover how to render different components conditionally or dynamically at runtime in Vue 3 using the `<component :is="componentName">` attribute for flexible UI design.
// src/components/DynamicComponentHost.vue
<template>
<div class="dynamic-component-host">
<h1>Dynamic Component Host</h1>
<div class="tabs">
<button @click="activeComponent = 'ComponentA'" :class="{ active: activeComponent === 'ComponentA' }">
Load Component A
</button>
<button @click="activeComponent = 'ComponentB'" :class="{ active: activeComponent === 'ComponentB' }">
Load Component B
</button>
</div>
<div class="component-wrapper">
<component :is="currentComponent" />
</div>
</div>
</template>
<script setup>
import { ref, computed } from 'vue';
import ComponentA from './ComponentA.vue';
import ComponentB from './ComponentB.vue';
// Using ref for component name string
const activeComponent = ref('ComponentA');
// Use computed property to return the actual component object
const currentComponent = computed(() => {
switch (activeComponent.value) {
case 'ComponentA':
return ComponentA;
case 'ComponentB':
return ComponentB;
default:
return ComponentA; // Default component
}
});
</script>
<style scoped>
.dynamic-component-host { border: 1px solid #ccc; padding: 20px; margin: 20px; }
.tabs button { margin-right: 10px; padding: 8px 15px; cursor: pointer; border: 1px solid #ddd; background: #f0f0f0; }
.tabs button.active { background: #007bff; color: white; border-color: #007bff; }
.component-wrapper { margin-top: 20px; padding: 15px; border: 1px dashed #999; }
</style>
// src/components/ComponentA.vue
<template>
<div class="component-a">
<h3>This is Component A</h3>
<p>Content specific to Component A.</p>
</div>
</template>
<script setup></script>
<style scoped> .component-a { color: blue; } </style>
// src/components/ComponentB.vue
<template>
<div class="component-b">
<h3>This is Component B</h3>
<p>Content specific to Component B.</p>
</div>
</template>
<script setup></script>
<style scoped> .component-b { color: green; } </style>
How it works: This snippet demonstrates how to dynamically render different Vue 3 components based on a reactive state. The `<component :is="currentComponent" />` syntax is used, where `currentComponent` is a computed property returning the actual imported component instance. This allows for creating tabbed interfaces, wizards, or other UIs where the displayed component changes at runtime, providing great flexibility.