How to Use Lazy Loading in Vue for Faster Apps
In Vue, you use
defineAsyncComponent to lazy load components, which loads them only when needed. This improves app speed by splitting code and loading parts on demand.Syntax
Use defineAsyncComponent from Vue to wrap the component import. This tells Vue to load the component only when it is needed in the UI.
Example parts:
defineAsyncComponent(() => import('./MyComponent.vue')): loadsMyComponentlazily.- Use the lazy component like a normal component in your template.
javascript
import { defineAsyncComponent } from 'vue'; const MyComponent = defineAsyncComponent(() => import('./MyComponent.vue')); export default { components: { MyComponent } };
Example
This example shows a Vue app that lazy loads a component only when a button is clicked. The component is not loaded until needed, saving initial load time.
vue
<template>
<div>
<button @click="show = true">Show Lazy Component</button>
<MyComponent v-if="show" />
</div>
</template>
<script setup>
import { ref, defineAsyncComponent } from 'vue';
const show = ref(false);
const MyComponent = defineAsyncComponent(() => import('./MyComponent.vue'));
</script>Output
<button>Show Lazy Component</button>
<!-- When button clicked -->
<!-- MyComponent content appears -->
Common Pitfalls
Common mistakes include:
- Not using
defineAsyncComponentand importing components normally, which disables lazy loading. - Forgetting to handle loading or error states, which can confuse users if the component takes time to load.
- Using lazy loading for very small components that do not improve performance.
Always consider user experience and add fallback UI if needed.
javascript
/* Wrong way: normal import disables lazy loading */ import MyComponent from './MyComponent.vue'; /* Right way: lazy load with defineAsyncComponent */ import { defineAsyncComponent } from 'vue'; const MyComponent = defineAsyncComponent(() => import('./MyComponent.vue'));
Quick Reference
- Import: Use
defineAsyncComponent(() => import('path')) - Use: Register lazy component normally in
componentsand use in template - Benefits: Smaller initial bundle, faster load
- Consider: Add loading/error UI for better UX
Key Takeaways
Use defineAsyncComponent with dynamic import to lazy load Vue components.
Lazy loading improves app speed by loading components only when needed.
Add loading or error states to handle delays gracefully.
Avoid lazy loading very small components that don't impact performance.
Use lazy loaded components just like normal components in your templates.