JAVASCRIPT
Dynamically Render Components Using Vue 3's `<component :is>`
Learn to efficiently switch between different Vue components at runtime using the `<component :is="componentName">` syntax, perfect for tabbed interfaces or conditional rendering.
// src/components/ComponentA.vue
<template>
<div style="border: 1px solid blue; padding: 10px; margin: 5px;">
<h3>Component A</h3>
<p>This is the content for Component A.</p>
</div>
</template>
<script setup>
// No specific script needed for this simple example
</script>
// src/components/ComponentB.vue
<template>
<div style="border: 1px solid green; padding: 10px; margin: 5px;">
<h3>Component B</h3>
<p>This is the content for Component B.</p>
<input type="text" placeholder="Type something..." />
</div>
</template>
<script setup>
// No specific script needed for this simple example
</script>
// src/App.vue
<template>
<div>
<button @click="currentComponent = 'ComponentA'">Show A</button>
<button @click="currentComponent = 'ComponentB'">Show B</button>
<keep-alive>
<component :is="currentComponent"></component>
</keep-alive>
</div>
</template>
<script setup>
import { ref } from 'vue';
import ComponentA from './components/ComponentA.vue';
import ComponentB from './components/ComponentB.vue';
const currentComponent = ref('ComponentA');
const components = {
ComponentA,
ComponentB
};
</script>
How it works: This snippet illustrates how to dynamically render Vue components using the special `<component :is="...">` element. By binding the `is` attribute to a reactive variable `currentComponent`, we can switch between `ComponentA` and `ComponentB` at runtime. The `<keep-alive>` wrapper is used to preserve the state of the dynamically loaded components when they are inactive, preventing re-rendering and data loss (e.g., the input value in Component B). The `components` object is created to map string names to the imported component references.