JAVASCRIPT

Implementing Dynamic Components with Vue 3

Discover how to dynamically render different components based on a reactive state using Vue 3's `<component :is="...">` element, perfect for tabbed views or flexible UI.

<template>
  <div>
    <button @click="activeComponent = 'ComponentA'">Show Component A</button>
    <button @click="activeComponent = 'ComponentB'">Show Component B</button>
    <button @click="activeComponent = 'ComponentC'">Show Component C</button>

    <hr>

    <component :is="activeComponent" />
  </div>
</template>

<script setup>
import { ref, defineAsyncComponent } from 'vue';
// For a real app, these would be in separate files
import ComponentA from './DynamicComponentA.vue';
import ComponentB from './DynamicComponentB.vue';

// Example of a simple component
const ComponentC = {
  template: `<div>This is Component C, defined inline!</div>`
};

const activeComponent = ref('ComponentA');

// Optionally, use async components for better performance
// const ComponentA = defineAsyncComponent(() => import('./DynamicComponentA.vue'));
</script>

<!-- src/components/DynamicComponentA.vue -->
<template>
  <div style="border: 1px solid blue; padding: 10px; margin-top: 10px;">
    <h3>Component A</h3>
    <p>Content for Component A.</p>
  </div>
</template>
<script setup></script>

<!-- src/components/DynamicComponentB.vue -->
<template>
  <div style="border: 1px solid green; padding: 10px; margin-top: 10px;">
    <h3>Component B</h3>
    <p>Content for Component B.</p>
  </div>
</template>
<script setup></script>
How it works: Vue 3's `<component :is="...">` element provides a powerful way to render components dynamically. By binding the `is` attribute to a reactive variable (e.g., `activeComponent`), you can switch the rendered component at runtime. This pattern is incredibly useful for building tabbed interfaces, wizards, or any UI where different components need to be displayed based on user interaction or application state. The example also briefly touches on `defineAsyncComponent` for performance optimization.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs