JAVASCRIPT
Mastering Dynamic and Asynchronous Components in Vue 3
Learn how to render components dynamically using `<component :is="...">` and improve performance by lazy-loading components asynchronously in Vue 3.
// components/HomeDashboard.vue
<template>
<div class="dashboard-card">
<h3>Home Dashboard</h3>
<p>Welcome to your personalized dashboard!</p>
</div>
</template>
<script setup></script>
<style scoped> .dashboard-card { border: 1px solid #eee; padding: 15px; margin: 10px; border-radius: 8px; background-color: #f9f9f9; } </style>
// components/AnalyticsPanel.vue
<template>
<div class="dashboard-card">
<h3>Analytics Panel</h3>
<p>Detailed insights and data visualizations.</p>
<p>(This component was loaded lazily!)</p>
</div>
</template>
<script setup></script>
<style scoped> .dashboard-card { border: 1px solid #eee; padding: 15px; margin: 10px; border-radius: 8px; background-color: #f0f8ff; } </style>
// App.vue
<template>
<div>
<h1>Dynamic Components Example</h1>
<button @click="activeComponent = 'HomeDashboard'">Show Home</button>
<button @click="activeComponent = 'AnalyticsPanel'">Show Analytics</button>
<div class="component-container">
<component :is="currentComponent" />
</div>
</div>
</template>
<script setup>
import { ref, shallowRef, computed } from 'vue';
import HomeDashboard from './components/HomeDashboard.vue';
// Define async components for lazy loading
const AsyncAnalyticsPanel = shallowRef(
defineAsyncComponent(() => import('./components/AnalyticsPanel.vue'))
);
const components = {
HomeDashboard,
AnalyticsPanel: AsyncAnalyticsPanel,
// You can add more components here
};
const activeComponent = ref('HomeDashboard');
const currentComponent = computed(() => {
return components[activeComponent.value];
});
import { defineAsyncComponent } from 'vue'; // Import defineAsyncComponent
</script>
<style>
.component-container {
margin-top: 20px;
padding: 20px;
border: 1px solid #ccc;
border-radius: 10px;
min-height: 150px;
}
</style>
How it works: This snippet illustrates the power of dynamic and asynchronous components in Vue 3. It uses `<component :is="currentComponent" />` to render different components based on the `activeComponent` state, allowing for highly flexible UI layouts. Additionally, the `AnalyticsPanel` is loaded asynchronously using `defineAsyncComponent`, which means its code is only fetched from the server when it's actually needed. This lazy loading technique significantly improves initial page load performance by reducing the main bundle size. The `shallowRef` is used for `AsyncAnalyticsPanel` to ensure the component instance itself is not deeply reactive, which is a performance optimization when dealing with component definitions.