JAVASCRIPT

Dynamically Render Components in Vue 3

Implement dynamic component rendering in Vue 3 using the `<component :is='...' />` attribute, enabling flexible UIs that load components conditionally or asynchronously.

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

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

// components/ComponentC.vue (for async example)
<template>
  <div style="border: 1px solid orange; padding: 10px; margin: 5px;">
    <h3>Async Loaded Component C</h3>
    <p>This component was loaded lazily.</p>
  </div>
</template>

// App.vue
<template>
  <div>
    <button @click="currentComponent = ComponentA">Load A</button>
    <button @click="currentComponent = ComponentB">Load B</button>
    <button @click="currentComponent = AsyncComponent">Load Async C</button>

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

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

const AsyncComponent = defineAsyncComponent(() =>
  import('./components/ComponentC.vue')
);

const currentComponent = ref(ComponentA); // Initial component, use actual component reference
</script>
How it works: This snippet illustrates how to dynamically render components in Vue 3 using the special `<component :is="..." />` element. By binding the `is` attribute to a reactive variable, you can switch between registered components at runtime. It also demonstrates `defineAsyncComponent` for lazy loading components, which can improve initial page load performance by only loading a component's code when it's actually needed.

Need help integrating this into your project?

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

Hire DigitalCodeLabs