JAVASCRIPT
Dynamic Component Rendering with Vue 3's <component :is>
Implement dynamic component rendering in Vue 3 using the special `<component :is>` attribute to display different components based on conditions or data, ideal for tabbed interfaces.
<template>
<div>
<h1>Dynamic Components</h1>
<button @click="activeComponent = 'ComponentA'">Show A</button>
<button @click="activeComponent = 'ComponentB'">Show B</button>
<button @click="activeComponent = 'ComponentC'">Show C</button>
<div class="dynamic-component-wrapper">
<component :is="activeComponent" message="Hello from parent!"></component>
</div>
</div>
</template>
<script setup>
import { ref } from 'vue';
// Import your components
import ComponentA from './ComponentA.vue';
import ComponentB from './ComponentB.vue';
import ComponentC from './ComponentC.vue';
const activeComponent = ref('ComponentA'); // Default component
// Register components locally (or globally if preferred)
// If using 'name' option in defineComponent, can use string directly
// Otherwise, need to map component objects.
const components = {
ComponentA,
ComponentB,
ComponentC,
};
// For the :is attribute, you can directly use the imported component object
// or, if you pass a string name, ensure the component is registered
// (e.g., in a components object like above, or globally).
// Here, we use the string name which implicitly maps to the imported objects
// thanks to Vue's automatic component resolution in script setup.
</script>
<style scoped>
.dynamic-component-wrapper {
border: 1px solid #eee;
padding: 20px;
margin-top: 20px;
min-height: 100px;
display: flex;
justify-content: center;
align-items: center;
}
button {
margin-right: 10px;
padding: 8px 15px;
cursor: pointer;
}
</style>
<!-- Example ComponentA.vue -->
<!-- <template>
<div style="color: blue;">Component A Content! Received: {{ message }}</div>
</template>
<script setup>
defineProps({ message: String });
</script> -->
<!-- Example ComponentB.vue -->
<!-- <template>
<div style="color: green;">Component B Content! Received: {{ message }}</div>
</template>
<script setup>
defineProps({ message: String });
</script> -->
<!-- Example ComponentC.vue -->
<!-- <template>
<div style="color: red;">Component C Content! Received: {{ message }}</div>
</template>
<script setup>
defineProps({ message: String });
</script> -->
How it works: This snippet demonstrates dynamic component rendering in Vue 3 using the special `<component :is>` attribute. This allows you to conditionally render different components based on a reactive data property (`activeComponent` in this case). When the value of `activeComponent` changes, Vue intelligently swaps out the currently rendered component with the new one. This pattern is highly useful for building tabbed interfaces, wizards, or any scenario where you need to switch between various content views without re-rendering the entire page, passing props as needed.