JAVASCRIPT
Dynamic Component Rendering with `<component :is="componentName">`
Learn how to dynamically render different components in Vue 3 based on reactive data using the special `<component :is="...">` element, enabling flexible UI structures.
// components/ViewA.vue
// <template>
// <div class="view-panel">
// <h2>This is View A</h2>
// <p>Content for view A.</p>
// </div>
// </template>
// <script setup>
// console.log('ViewA created');
// </script>
// <style scoped> .view-panel { border: 1px solid blue; padding: 10px; margin: 10px 0; } </style>
// components/ViewB.vue
// <template>
// <div class="view-panel">
// <h2>This is View B</h2>
// <p>Content for view B.</p>
// </div>
// </template>
// <script setup>
// console.log('ViewB created');
// </script>
// <style scoped> .view-panel { border: 1px solid green; padding: 10px; margin: 10px 0; } </style>
// App.vue
// <template>
// <div>
// <button @click="currentView = 'ViewA'">Show View A</button>
// <button @click="currentView = 'ViewB'">Show View B</button>
//
// <p>Currently active view: {{ currentView }}</p>
//
// <!-- Dynamically render component based on currentView -->
// <component :is="activeComponent"></component>
//
// <!-- Optional: Keep alive for performance if components are frequently switched -->
// <!-- <KeepAlive> -->
// <!-- <component :is="activeComponent"></component> -->
// <!-- </KeepAlive> -->
// </div>
// </template>
//
// <script setup>
// import { ref, computed } from 'vue';
// import ViewA from './components/ViewA.vue';
// import ViewB from './components/ViewB.vue';
//
// const currentView = ref('ViewA');
//
// // Map string names to actual component objects
// const components = {
// ViewA,
// ViewB
// };
//
// const activeComponent = computed(() => components[currentView.value]);
// </script>
How it works: This snippet demonstrates dynamic component rendering in Vue 3 using the special `<component>` element with the `:is` prop. By binding `:is` to a reactive property (like `activeComponent` derived from `currentView`), you can switch which component is rendered at runtime. This is highly beneficial for creating flexible user interfaces such as dashboards, multi-step forms, or content areas where the displayed component changes based on user interaction or application state. The optional `<KeepAlive>` wrapper can be used to preserve the state of inactive dynamic components.