JAVASCRIPT
Vue 3 Dynamic Components with <component :is='...'/>
Discover how to dynamically render different components based on a reactive value in Vue 3 using the <component :is='...'/> attribute, enabling flexible and modular UI development.
// src/components/ComponentA.vue
<template>
<div style="border: 1px solid blue; padding: 10px; margin: 5px;">
<h3>Component A</h3>
<p>This is the first dynamic component.</p>
<button @click="$emit('change', 'ComponentB')">Go to B</button>
</div>
</template>
<script setup>
import { defineEmits } from 'vue';
defineEmits(['change']);
</script>
// src/components/ComponentB.vue
<template>
<div style="border: 1px solid green; padding: 10px; margin: 5px;">
<h3>Component B</h3>
<p>This is the second dynamic component.</p>
<button @click="$emit('change', 'ComponentA')">Go to A</button>
</div>
</template>
<script setup>
import { defineEmits } from 'vue';
defineEmits(['change']);
</script>
// src/App.vue
<template>
<div>
<h1>Dynamic Component Example</h1>
<p>Current component: <strong>{{ currentComponent.name }}</strong></p>
<button @click="currentComponent = ComponentA">Load A</button>
<button @click="currentComponent = ComponentB">Load B</button>
<hr>
<component :is="currentComponent" @change="handleComponentChange"></component>
</div>
</template>
<script setup>
import { ref, shallowRef } from 'vue';
import ComponentA from './components/ComponentA.vue';
import ComponentB from './components/ComponentB.vue';
// Use shallowRef for component references to avoid unnecessary deep reactivity overhead
const currentComponent = shallowRef(ComponentA);
function handleComponentChange(componentName) {
if (componentName === 'ComponentA') {
currentComponent.value = ComponentA;
} else if (componentName === 'ComponentB') {
currentComponent.value = ComponentB;
}
}
</script>
How it works: This snippet demonstrates how to use Vue 3's `<component :is="...">` attribute to render components dynamically. It defines two simple components, `ComponentA` and `ComponentB`, and then uses a `shallowRef` in `App.vue` to store the reference to the currently active component. Buttons and an event handler dynamically switch which component is rendered, providing a flexible way to manage UI elements based on state without complex conditional rendering logic.