JAVASCRIPT
Dynamically Switching Components with Vue 3
Discover how to dynamically render different components in Vue 3 using the `<component :is>` attribute, enhancing UI flexibility and code organization.
// components/ComponentA.vue
// <template>
// <div style="border: 1px solid blue; padding: 10px;">
// <h2>Component A</h2>
// <p>I am the first component. Message: {{ message }}</p>
// </div>
// </template>
// <script setup>
// import { defineProps } from 'vue';
// defineProps({ message: String });
// </script>
// components/ComponentB.vue
// <template>
// <div style="border: 1px solid green; padding: 10px;">
// <h2>Component B</h2>
// <p>I am the second component. Value: {{ value }}</p>
// </div>
// </template>
// <script setup>
// import { defineProps } from 'vue';
// defineProps({ value: Number });
// </script>
// App.vue (Parent Component)
<template>
<div>
<h1>Dynamic Component Example</h1>
<button @click="activeComponent = 'ComponentA'">Show Component A</button>
<button @click="activeComponent = 'ComponentB'">Show Component B</button>
<hr />
<component :is="activeComponent" :message="'Hello from App!'" :value="42"></component>
<p>Currently active: {{ activeComponent }}</p>
</div>
</template>
<script setup>
import { ref } from 'vue';
import ComponentA from './components/ComponentA.vue';
import ComponentB from './components/ComponentB.vue';
const activeComponent = ref('ComponentA');
</script>
How it works: This snippet demonstrates Vue 3's powerful `component :is` attribute, allowing you to dynamically render different components based on a reactive value. By binding `:is` to `activeComponent`, you can switch between `ComponentA` and `ComponentB` with a simple button click. This pattern is incredibly useful for building tabbed interfaces, wizards, or highly configurable layouts where the active view needs to change at runtime, promoting modularity and flexible UI design.