JAVASCRIPT
Lazy Load Vue Components with defineAsyncComponent
Improve Vue 3 application performance by asynchronously loading components only when needed, reducing initial bundle size and enhancing user experience.
// App.vue
<template>
<div>
<h1>Welcome to the App!</h1>
<button @click="showHeavyComponent = !showHeavyComponent">
{{ showHeavyComponent ? 'Hide' : 'Show' }} Heavy Component
</button>
<div v-if="showHeavyComponent">
<AsyncHeavyComponent />
</div>
<p>Content below the lazy-loaded component.</p>
</div>
</template>
<script setup>
import { ref, defineAsyncComponent } from 'vue';
// The component will only be fetched from the server when it's first rendered.
const AsyncHeavyComponent = defineAsyncComponent(() =>
import('./components/HeavyComponent.vue')
);
const showHeavyComponent = ref(false);
</script>
// components/HeavyComponent.vue (Imagine this component has lots of code/dependencies)
<template>
<div style="border: 1px solid blue; padding: 20px; margin-top: 10px;">
<h2>This is a Lazy-Loaded Component</h2>
<p>It was only loaded when you clicked the button!</p>
<p>Current Time: {{ currentTime }}</p>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
const currentTime = ref('');
onMounted(() => {
currentTime.value = new Date().toLocaleTimeString();
});
</script>
How it works: This snippet illustrates how to lazy-load (or asynchronously load) a Vue component using `defineAsyncComponent`. This technique is crucial for optimizing application performance by deferring the loading of non-critical components until they are actually needed, such as when a user navigates to a specific route or clicks a button. This reduces the initial bundle size and improves the initial page load time, resulting in a snappier user experience. The component defined by `defineAsyncComponent` will only be fetched and processed by the browser when it is first rendered.