JAVASCRIPT

Dynamic Component Rendering with Vue 3

Discover how to dynamically switch between different components based on a condition or user interaction using Vue 3's built-in `<component :is="...">` element.

// ComponentA.vue
<template>
  <div style="border: 1px solid blue; padding: 10px;">
    <h3>Component A</h3>
    <p>This is the content of Component A.</p>
  </div>
</template>

<script setup>
// Component A logic
</script>

// ComponentB.vue
<template>
  <div style="border: 1px solid green; padding: 10px;">
    <h3>Component B</h3>
    <p>This is the content of Component B.</p>
  </div>
</template>

<script setup>
// Component B logic
</script>

// App.vue (Parent Component)
<template>
  <div>
    <button @click="currentComponent = 'ComponentA'">Show A</button>
    <button @click="currentComponent = 'ComponentB'">Show B</button>

    <p>Currently showing: {{ currentComponent }}</p>

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

<script setup>
import { ref } from 'vue';
import ComponentA from './ComponentA.vue';
import ComponentB from './ComponentB.vue';

const currentComponent = ref('ComponentA');

// Register components locally if not using global registration
// This is automatically handled by Vite/Webpack for imported components in <script setup>
</script>
How it works: This snippet illustrates how to render components dynamically in Vue 3. The `<component :is="currentComponent" />` tag is the core feature, where `currentComponent` is a reactive variable holding the name (or component object) of the component to render. By changing the value of `currentComponent` (e.g., via button clicks), Vue automatically swaps the rendered component. This is highly useful for creating tabbed interfaces, wizards, or dashboards where different content panels need to be displayed based on user interaction or state.

Need help integrating this into your project?

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

Hire DigitalCodeLabs