JAVASCRIPT
Render Dynamic Components with Vue 3 `is` Attribute
Utilize Vue 3's dynamic components feature with the `is` attribute to switch between different components conditionally at runtime, enhancing UI flexibility.
<!-- App.vue -->
<template>
<div>
<button @click="currentComponent = 'ComponentA'">Show A</button>
<button @click="currentComponent = 'ComponentB'">Show B</button>
<component :is="currentComponent" />
</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 static components if no reactivity is needed for the component itself
// You could also store them by string names if registered globally or dynamically imported
// const currentComponent = ref('ComponentA');
// const components = { ComponentA, ComponentB }; // Map string names to actual components
// <component :is="components[currentComponent]" />
</script>
<!-- components/ComponentA.vue -->
<template>
<div style="border: 1px solid blue; padding: 10px; margin-top: 10px;">
<h3>Component A</h3>
<p>This is the content of Component A.</p>
</div>
</template>
<script setup>
import { onMounted } from 'vue';
onMounted(() => console.log('ComponentA mounted'));
</script>
<!-- components/ComponentB.vue -->
<template>
<div style="border: 1px solid green; padding: 10px; margin-top: 10px;">
<h3>Component B</h3>
<p>This is the content of Component B with a counter: {{ count }}</p>
<button @click="count++">Increment</button>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
const count = ref(0);
onMounted(() => console.log('ComponentB mounted'));
</script>
How it works: This snippet illustrates how to render dynamic components in Vue 3 using the special `<component>` element with the `is` attribute. By binding `is` to a reactive variable (e.g., `currentComponent`), you can switch which component is rendered at runtime. This is extremely useful for building tabbed interfaces, wizards, or dashboards where different views need to be displayed based on user interaction or application state. `markRaw` is used here to prevent the component object itself from being made reactive, which can be an optimization for static component references.