JAVASCRIPT
Dynamically Render Components Based on User Interaction
Learn how to dynamically switch between different Vue 3 components at runtime using the `<component :is="...">` element, perfect for flexible UI layouts.
// src/components/ComponentA.vue
<template>
<div style="padding: 20px; border: 1px solid blue;">
<h3>Component A</h3>
<p>This is the content of Component A.</p>
</div>
</template>
// src/components/ComponentB.vue
<template>
<div style="padding: 20px; border: 1px solid green;">
<h3>Component B</h3>
<p>This is the content of Component B.</p>
</div>
</template>
// src/App.vue
<template>
<div>
<h1>Dynamic Component Example</h1>
<button @click="activeComponent = 'ComponentA'">Show Component A</button>
<button @click="activeComponent = 'ComponentB'">Show Component B</button>
<hr />
<KeepAlive>
<component :is="activeComponent"></component>
</KeepAlive>
</div>
</template>
<script setup>
import { ref } from 'vue';
import ComponentA from './components/ComponentA.vue';
import ComponentB from './components/ComponentB.vue';
const activeComponent = ref('ComponentA'); // Default active component
</script>
<style>
button { margin-right: 10px; padding: 8px 15px; }
hr { margin: 20px 0; }
</style>
How it works: This snippet demonstrates how to dynamically render components in Vue 3 using the special `<component :is="componentName">` element. By binding `activeComponent` to the `:is` prop, Vue intelligently swaps out the rendered component based on the reactive value. The `KeepAlive` wrapper is optionally used here to preserve the state of inactive components, preventing them from being re-mounted each time they are switched, which can be useful for performance and user experience.