JAVASCRIPT
Dynamically Switching Components with Vue 3's `is` Attribute
Learn how to use Vue 3's special `is` attribute to render different components conditionally, creating flexible interfaces like tabbed navigation or multi-step forms.
// ComponentA.vue
<template>
<div>This is Component A</div>
</template>
// ComponentB.vue
<template>
<div>This is Component B</div>
</template>
// App.vue
<template>
<button @click="currentTab = 'ComponentA'">Show A</button>
<button @click="currentTab = 'ComponentB'">Show B</button>
<keep-alive>
<component :is="currentTabComponent"></component>
</keep-alive>
</template>
<script setup>
import { ref, computed } from 'vue';
import ComponentA from './ComponentA.vue';
import ComponentB from './ComponentB.vue';
const currentTab = ref('ComponentA');
const currentTabComponent = computed(() => {
return currentTab.value === 'ComponentA' ? ComponentA : ComponentB;
});
</script>
<style scoped>
button { margin-right: 10px; padding: 8px 15px; cursor: pointer; }
div { margin-top: 20px; padding: 15px; border: 1px solid #eee; background-color: #f9f9f9; }
</style>
How it works: The `<component :is="componentName"></component>` element allows you to render a different component dynamically based on a variable. This is extremely useful for building tabbed interfaces, wizards, or dashboards where the content changes without full page reloads. Using `<keep-alive>` optionally preserves the state of inactive components, preventing them from being re-rendered each time they are switched away from and back to.