JAVASCRIPT
Dynamically Rendering Components with <component :is>
Learn how to use Vue 3's `<component :is="componentName">` syntax to dynamically switch between different components at runtime, enabling flexible and modular UI development.
// components/ComponentA.vue
// <template>
// <div style="padding: 10px; border: 1px solid blue;">
// <h2>Component A</h2>
// <p>This is content from Component A.</p>
// </div>
// </template>
// <script setup>
// import { onMounted } from 'vue';
// onMounted(() => console.log('Component A mounted'));
// </script>
// components/ComponentB.vue
// <template>
// <div style="padding: 10px; border: 1px solid green;">
// <h2>Component B</h2>
// <p>This is content from Component B.</p>
// </div>
// </template>
// <script setup>
// import { onMounted } from 'vue';
// onMounted(() => console.log('Component B mounted'));
// </script>
// App.vue (Parent Component)
<template>
<div>
<button @click="toggleComponent">Toggle Component</button>
<div style="margin-top: 20px;">
<!-- Using KeepAlive to preserve state -->
<KeepAlive>
<component :is="currentComponent"></component>
</KeepAlive>
</div>
</div>
</template>
<script setup>
import { ref, markRaw } from 'vue';
import ComponentA from './components/ComponentA.vue';
import ComponentB from './components/ComponentB.vue';
const currentComponent = ref(markRaw(ComponentA)); // Use markRaw for imported components
const isShowingA = ref(true);
function toggleComponent() {
isShowingA.value = !isShowingA.value;
currentComponent.value = isShowingA.value ? markRaw(ComponentA) : markRaw(ComponentB);
}
</script>
How it works: This snippet demonstrates how to dynamically render different components in Vue 3 using the `<component :is="componentName">` element. It toggles between `ComponentA` and `ComponentB` based on a reactive state. The `markRaw` utility is used to prevent the component instances from becoming reactive, which is a best practice for dynamic components to avoid unnecessary overhead. `KeepAlive` is also shown to preserve component state when switching.