Build Vue's defineAsyncComponent: a shared loader, delayed loading state, timeout, onError retries and Suspense

hardAbout 50 minutesUpdated CodingProvueasync-componentscode-splittingsuspensepromises
Not solved

Share this question

Problem

defineAsyncComponent(() => import("./Chart.vue")) is how Vue apps split a heavy component into its own chunk. The wrapper it returns decides what to render while the chunk loads: nothing at first, a loading component if the wait is long enough to notice, an error component on failure or timeout, and the real component once it arrives. It also deduplicates the request and can retry. Build it.

const Chart = defineAsyncComponent({
  loader: () => import("./Chart.js"),
  loadingComponent: Spinner,
  errorComponent: LoadFailed,
  delay: 200,
  timeout: 3000,
});
const render = Chart.setup({ data }, instance);
render(); // null: under 200ms the spinner would only flash
// 200ms later: { type: Spinner, props: null }; after the load: { type: ChartComponent, props: { data } }

Ref. UR-1459 · © UIRound · uiround.com/questions/build-vues-defineasynccomponent-a-shared-loader-delayed-loading-state-timeout-onerror-retries-and-suspense

Stuck? Take a hint

Try it in the editor

Run your code as often as you like. Submitting it to the full test suite is part of Pro.

Private, and saved in this browser as you type. All your notes are on My lists.

Every question and answer7 days, one payment