JAVASCRIPT
Dynamic Component Rendering in Vue 3 with `<component :is>`
Render different components conditionally and dynamically at runtime in Vue 3 applications using the powerful `<component :is='...'/>` attribute.
<template>
<div>
<h1>Dynamic Components Example</h1>
<button @click="currentComp = 'ComponentA'">Show Component A</button>
<button @click="currentComp = 'ComponentB'">Show Component B</button>
<component :is="currentComp"></component>
</div>
</template>
<script setup>
import { ref, shallowRef } from 'vue';
import ComponentA from './ComponentA.vue'; // Assuming these exist
import ComponentB from './ComponentB.vue'; // Assuming these exist
// Register components globally or import them
const components = {
ComponentA,
ComponentB
};
// Use shallowRef for component references to avoid unnecessary deep reactivity
// which can be costly for complex component objects.
const currentComp = shallowRef(components.ComponentA);
</script>
<!-- ComponentA.vue -->
<template>
<div style="border: 1px solid blue; padding: 10px; margin-top: 10px;">
<h3>This is Component A</h3>
<p>Content specific to Component A.</p>
</div>
</template>
<script setup>
// Component A logic
</script>
<!-- ComponentB.vue -->
<template>
<div style="border: 1px solid green; padding: 10px; margin-top: 10px;">
<h3>This is Component B</h3>
<p>Content specific to Component B.</p>
</div>
</template>
<script setup>
// Component B logic
</script>
How it works: This snippet demonstrates how to render dynamic components in Vue 3 using the `<component :is="..." />` element. By binding the `is` attribute to a reactive variable that holds the name (string) or component definition (object) of a component, you can switch between different components at runtime. This is particularly useful for creating tabbed interfaces, wizards, or dashboards where different content panels need to be rendered based on user interaction or application state. Using `shallowRef` is often recommended for component references to optimize performance.