JAVASCRIPT
Dynamically Swapping Components in Vue 3 with `:is`
Learn how to render different components based on a reactive state using Vue 3's dynamic component feature with the :is attribute, ideal for tabbed interfaces, wizards, or complex forms.
// ComponentA.vue
<template>
<div class="component-box">
<h3>Component A</h3>
<p>This is the content for Component A.</p>
</div>
</template>
<style scoped>
.component-box { border: 1px solid #4CAF50; padding: 20px; margin: 10px; background-color: #e8f5e9; }
</style>
// ComponentB.vue
<template>
<div class="component-box">
<h3>Component B</h3>
<p>This is the content for Component B.</p>
</div>
</template>
<style scoped>
.component-box { border: 1px solid #2196F3; padding: 20px; margin: 10px; background-color: #e3f2fd; }
</style>
// ParentComponent.vue
<template>
<div>
<h2>Dynamic Component Example</h2>
<button @click="currentComponent = 'ComponentA'">Show A</button>
<button @click="currentComponent = 'ComponentB'">Show B</button>
<component :is="currentComponent" />
</div>
</template>
<script setup>
import { ref } from 'vue';
import ComponentA from './ComponentA.vue';
import ComponentB from './ComponentB.vue';
const currentComponent = ref('ComponentA');
// Register components locally (alternatively, global registration can be used)
const components = {
ComponentA,
ComponentB,
};
</script>
<style scoped>
button {
margin: 0 5px 15px 0;
padding: 8px 15px;
cursor: pointer;
}
</style>
How it works: Vue 3 allows you to render components dynamically using the special `<component>` element with the `:is` attribute. The value bound to `:is` can be either the name of a registered component (as a string) or the component's actual definition object. This snippet demonstrates how a `ParentComponent` can switch between `ComponentA` and `ComponentB` by simply updating a reactive `currentComponent` string. When the `currentComponent` value changes, Vue automatically unmounts the previous component and mounts the new one, making it ideal for building flexible UIs like tabbed interfaces or multi-step forms.