JAVASCRIPT
Render Dynamic Components with Vue 3's `is` Attribute
Learn how to use Vue 3's special `is` attribute to dynamically switch between multiple components at runtime, enabling flexible UI construction based on conditions or user interaction.
// ComponentA.vue
<template>
<div style="border: 1px solid blue; padding: 10px;">
<h3>Component A</h3>
<p>This is content from Component A.</p>
</div>
</template>
// ComponentB.vue
<template>
<div style="border: 1px solid green; padding: 10px;">
<h3>Component B</h3>
<p>This is content from Component B.</p>
</div>
</template>
// App.vue (example usage)
<template>
<div>
<h1>Dynamic Component Example</h1>
<button @click="toggleComponent">Toggle Component</button>
<p>Currently showing: {{ currentComponent.name }}</p>
<keep-alive>
<component :is="currentComponent"></component>
</keep-alive>
</div>
</template>
<script setup>
import { ref, markRaw } from 'vue';
import ComponentA from './ComponentA.vue';
import ComponentB from './ComponentB.vue';
const currentComponent = ref(markRaw(ComponentA));
const toggleComponent = () => {
if (currentComponent.value === ComponentA) {
currentComponent.value = markRaw(ComponentB);
} else {
currentComponent.value = markRaw(ComponentA);
}
};
</script>
How it works: This snippet demonstrates rendering dynamic components using the `<component :is="currentComponent"></component>` syntax. `currentComponent` is a reactive ref holding the actual component definition (e.g., `ComponentA` or `ComponentB`). The `toggleComponent` function switches between them. `markRaw` is used to prevent the component definition from being deeply observed by Vue's reactivity system, which is good practice for component objects used with `is`. `keep-alive` ensures that switched-out components preserve their state.