JAVASCRIPT
Dynamically Rendering Components in Vue 3
Learn to dynamically switch between different components in Vue 3 using the special `is` attribute, enabling highly flexible UIs based on application state or user interaction.
// src/components/ComponentA.vue
<template>
<div style="border: 1px solid blue; padding: 10px; margin-bottom: 10px;">
<h3>Component A</h3>
<p>This is content from Component A.</p>
</div>
</template>
// src/components/ComponentB.vue
<template>
<div style="border: 1px solid green; padding: 10px; margin-bottom: 10px;">
<h3>Component B</h3>
<p>This is content from Component B.</p>
</div>
</template>
// src/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 switchComponent = () => {
currentComponent.value = currentComponent.value === ComponentA ? markRaw(ComponentB) : markRaw(ComponentA)
}
</script>
<template>
<div>
<h1>Dynamic Components</h1>
<button @click="switchComponent">Switch Component</button>
<hr>
<component :is="currentComponent"></component>
</div>
</template>
How it works: This snippet demonstrates dynamic component rendering using Vue's built-in `<component>` element and the `is` attribute. The `is` attribute binds to a reactive variable, `currentComponent`, which holds the component definition to be rendered. Here, `markRaw` is used to prevent the component object itself from becoming reactive, as it doesn't need to be. When `currentComponent` changes, Vue intelligently swaps the rendered component, making this pattern ideal for building tab interfaces, wizard steps, or dashboards where different content panels need to be displayed dynamically. This approach provides great flexibility for managing UI complexity.