javascript / expert
Snippet
Resilient Async Components with Error Handling
Expert application architecture requires robust handling of network failures. defineAsyncComponent allows you to define complex loading states, timeouts, and automatic retry logic for dynamically imported components, ensuring the UI remains stable even when chunks fail to load.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import { defineAsyncComponent } from 'vue';import ErrorComp from './Error.vue';import LoadingComp from './Loading.vue';const AsyncChart = defineAsyncComponent({loader: () => import('./BigChart.vue'),loadingComponent: LoadingComp,errorComponent: ErrorComp,delay: 200,timeout: 3000,onError(error, retry, fail, attempts) {if (attempts <= 3) retry();else fail();}});
vue
Breakdown
1
onError(error, retry, fail, attempts) {
Intercepts loading failures to implement custom recovery logic.
2
if (attempts <= 3) retry();
Programmatically triggers a reload attempt if the previous one failed.
3
timeout: 3000,
Specifies a maximum duration before the error component is displayed.