VUE
Rendering Dynamic Components in Vue 3
Master rendering different components conditionally or based on data using Vue 3's dynamic <component :is="..."> syntax for flexible UI structures.
<!-- App.vue -->
<template>
<div>
<button @click="activeComponent = 'ComponentA'">Show A</button>
<button @click="activeComponent = 'ComponentB'">Show B</button>
<div style="border: 1px solid #ccc; padding: 20px; margin-top: 20px;">
<component :is="activeComponent"></component>
</div>
</div>
</template>
<script setup>
import { ref, markRaw } from 'vue';
import ComponentA from './components/ComponentA.vue';
import ComponentB from './components/ComponentB.vue';
// Using markRaw to prevent ComponentA/B from being made reactive
// which is unnecessary and can cause performance issues if components are large.
const activeComponent = ref(markRaw(ComponentA));
// Alternative: activeComponent = ref('ComponentA'); then use object in :is binding { ComponentA, ComponentB }
// Function to switch component
// const switchComponent = (componentName) => {
// activeComponent.value = componentName === 'A' ? markRaw(ComponentA) : markRaw(ComponentB);
// };
</script>
<!-- components/ComponentA.vue -->
<template>
<p>This is Component A</p>
</template>
<script setup>
// Component A logic
</script>
<!-- components/ComponentB.vue -->
<template>
<p>This is Component B</p>
</template>
<script setup>
// Component B logic
</script>
How it works: Vue's `<component :is="activeComponent">` syntax allows you to render components dynamically. The `activeComponent` variable, which can be a string name or a component object, determines which component is rendered. This is incredibly useful for tabbed interfaces, wizards, or dashboards where the displayed content changes based on user interaction or data. `markRaw` is used here to prevent the component instances themselves from becoming reactive, which is a good practice for performance when dealing with component definitions.