JAVASCRIPT
Dynamic Component Loading and Async Components in Vue 3
Learn to dynamically render components based on data and asynchronously load them on demand in Vue 3 for improved performance and flexible UI design.
// ComponentA.vue
<template><div><h3>Component A Content</h3><p>This is the first dynamic component.</p></div></template>
// ComponentB.vue
<template><div><h3>Component B Content</h3><p>This is the second dynamic component.</p></div></template>
// ParentComponent.vue
<script setup>
import { ref, defineAsyncComponent } from 'vue';
import ComponentA from './ComponentA.vue';
// Define an asynchronous component. It will only be loaded when needed.
const AsyncComponentB = defineAsyncComponent(() =>
import('./ComponentB.vue')
);
const activeComponentName = ref('ComponentA'); // Initial active component
const components = {
ComponentA,
ComponentB: AsyncComponentB, // Use the async component here
};
const selectComponent = (name) => {
activeComponentName.value = name;
};
</script>
<template>
<div>
<h1>Dynamic Components</h1>
<button @click="selectComponent('ComponentA')">Show Component A</button>
<button @click="selectComponent('ComponentB')">Show Component B (Async)</button>
<div class="component-container">
<component :is="components[activeComponentName]" />
</div>
</div>
</template>
How it works: This snippet demonstrates two powerful features for managing components in Vue 3: dynamic components and asynchronous loading. The `<component :is="...">` element allows you to render a component dynamically based on the value of a bound property (`activeComponentName`). This is useful for building tab interfaces, wizards, or dashboards where the active view changes without full page reloads. Additionally, `defineAsyncComponent` is used to lazy-load `ComponentB`. This means the JavaScript for `ComponentB` will only be fetched from the server when it's actually needed (i.e., when `selectComponent('ComponentB')` is called), significantly improving initial page load times and overall application performance, especially for large applications with many routes or features.