JAVASCRIPT
Render Dynamic Components Based on Data
Learn how to dynamically render different Vue 3 components based on data using the `<component :is="...">` element, enabling flexible and modular UI structures in your application.
// src/components/ComponentA.vue
<template>
<div style="background-color: lightblue; padding: 15px; margin: 5px;">
<h3>Component A</h3>
<p>This is component A's content.</p>
</div>
</template>
<script setup>
// Component logic for A
</script>
// src/components/ComponentB.vue
<template>
<div style="background-color: lightcoral; padding: 15px; margin: 5px;">
<h3>Component B</h3>
<p>This is component B's content.</p>
</div>
</template>
<script setup>
// Component logic for B
</script>
// src/App.vue
<template>
<div>
<h1>Dynamic Component Example</h1>
<button @click="toggleComponent">Toggle Component</button>
<div style="border: 1px solid #ddd; padding: 20px; margin-top: 20px;">
<component :is="currentComponent"></component>
</div>
</div>
</template>
<script setup>
import { ref, shallowRef } from 'vue';
import ComponentA from './components/ComponentA.vue';
import ComponentB from './components/ComponentB.vue';
const currentComponent = shallowRef(ComponentA);
const toggleComponent = () => {
currentComponent.value = currentComponent.value === ComponentA ? ComponentB : ComponentA;
};
</script>
How it works: This snippet demonstrates Vue 3's `<component :is="...">` feature for dynamic component rendering. It allows you to switch between different components at runtime based on a data property. `shallowRef` is used here for `currentComponent` to optimize performance, as its value will only be switched between component definitions (objects) rather than deeply tracked. When the button is clicked, `currentComponent` changes, and Vue automatically renders the corresponding component, providing a flexible way to manage UI variations.