0 day streak
javascript / intermediate
Snippet

Handling Loading and Error States in Async Components

Async components help split your code into smaller chunks. By providing a loading and error component, you improve user experience during network latency or failure. The 'delay' property prevents the loading spinner from flickering on fast connections.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
import { defineAsyncComponent } from 'vue';
import LoadingSpinner from './LoadingSpinner.vue';
import ErrorMessage from './ErrorMessage.vue';
const AsyncChart = defineAsyncComponent({
loader: () => import('./components/BigChart.vue'),
loadingComponent: LoadingSpinner,
errorComponent: ErrorMessage,
delay: 200,
timeout: 3000
});
vue
Breakdown
1
loader: () => import(...)
The function that performs the actual dynamic import of the component.
2
delay: 200,
Wait time in milliseconds before showing the loading component.
3
timeout: 3000
If the loader takes longer than this, the error component is displayed.