JAVASCRIPT
Dynamically Render Components with Vue 3 `component` Tag
Learn to dynamically load and render different Vue 3 components based on data or user interaction using the `<component :is="...">` pattern.
// components/HomeDashboard.vue
<template>
<div class="dashboard-card">
<h3>Home Dashboard</h3>
<p>Welcome to your personalized dashboard!</p>
</div>
</template>
// components/AnalyticsView.vue
<template>
<div class="analytics-card">
<h3>Analytics Overview</h3>
<p>Detailed performance metrics displayed here.</p>
</div>
</template>
// App.vue
<template>
<div id="app">
<button @click="currentTab = 'HomeDashboard'">Home</button>
<button @click="currentTab = 'AnalyticsView'">Analytics</button>
<keep-alive>
<component :is="activeComponent"></component>
</keep-alive>
</div>
</template>
<script setup>
import { ref, computed } from 'vue';
import HomeDashboard from './components/HomeDashboard.vue';
import AnalyticsView from './components/AnalyticsView.vue';
const currentTab = ref('HomeDashboard');
const components = {
HomeDashboard,
AnalyticsView,
};
const activeComponent = computed(() => components[currentTab.value]);
</script>
<style>
.dashboard-card, .analytics-card {
border: 1px solid #eee;
padding: 20px;
margin-top: 20px;
border-radius: 8px;
}
</style>
How it works: This snippet demonstrates how to dynamically render different Vue 3 components based on a reactive state variable. The `<component :is="activeComponent"></component>` tag is key, where `activeComponent` is a computed property that resolves to the actual component instance to render. This pattern is incredibly useful for building tabbed interfaces, dashboards, or any scenario where you need to swap out entire sections of your UI at runtime. Using `<keep-alive>` around the dynamic component ensures that inactive components retain their state, preventing unnecessary re-renders when switching between them.