JAVASCRIPT
Dynamic Components with `is` attribute
Discover how to dynamically switch between different Vue 3 components at runtime using the special `is` attribute, allowing for flexible UI structures and conditional rendering.
// components/ComponentA.vue
<template>
<div style="border: 1px solid blue; padding: 10px; margin: 10px;">
<h3>Component A</h3>
<p>This is content from Component A.</p>
</div>
</template>
// components/ComponentB.vue
<template>
<div style="border: 1px solid green; padding: 10px; margin: 10px;">
<h3>Component B</h3>
<p>This is content from Component B.</p>
</div>
</template>
// App.vue
<script setup>
import { ref, markRaw } from 'vue';
import ComponentA from './components/ComponentA.vue';
import ComponentB from './components/ComponentB.vue';
const currentComponent = ref(markRaw(ComponentA));
const toggleComponent = () => {
if (currentComponent.value === ComponentA) {
currentComponent.value = markRaw(ComponentB);
} else {
currentComponent.value = markRaw(ComponentA);
}
};
</script>
<template>
<div>
<h1>Dynamic Component Example</h1>
<button @click="toggleComponent">Toggle Component</button>
<KeepAlive>
<component :is="currentComponent" />
</KeepAlive>
</div>
</template>
How it works: This snippet shows how to use Vue's `<component :is="...">` attribute to render dynamic components. It imports two components, `ComponentA` and `ComponentB`, and uses a `ref` named `currentComponent` to hold the currently active component. The `markRaw` utility is used to prevent the component instances from becoming reactive, which is a performance optimization when dealing with component definitions. A button toggles the value of `currentComponent`, causing the `<component>` tag to render the corresponding component. Using `<KeepAlive>` around the dynamic component ensures that inactive component instances are cached instead of being unmounted.