#Loading with LazyComponent
4 messages · Page 1 of 1 (latest)
Hi @fresh cosmos. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
In Nuxt, you don't need to manually implement the <Suspense> component with <RouterView> as shown in your example, because Nuxt already handles this for you through the <NuxtPage> component.
The <NuxtPage> component (which is Nuxt's equivalent of <RouterView>) already includes <Suspense> under the hood. According to the documentation:
<NuxtPage> includes the following components:
<template>
<RouterView #default="{ Component }">
<!-- Optional, when using transitions -->
<Transition>
<!-- Optional, when using keep-alive -->
<KeepAlive>
<Suspense>
<component :is="Component" />
</Suspense>
</KeepAlive>
</Transition>
</RouterView>
</template>
If you want to show a loading state while your components or pages are loading, you have several options:
- Use
<NuxtLoadingIndicator>for page navigation loading:
<template>
<div>
<NuxtLoadingIndicator />
<NuxtPage />
</div>
</template>
- For lazy-loaded components, you can use the
defineAsyncComponentwith a loading component:
<script setup>
const AsyncComponent = defineAsyncComponent({
loader: () => import('./components/MyComponent.vue'),
loadingComponent: LoadingComponent,
suspensible: false // Important to use your own loading component
})
</script>
As noted in a Stack Overflow post, you need to add suspensible: false to make your loading component show up instead of relying on the parent Suspense component's loading state Stack Overflow Post.
- For data fetching, you can handle loading states manually with
useLazyFetch:
<script setup>
const { status, data } = useLazyFetch('/api/data')
</script>
<template>
<div v-if="status === 'pending'">
Loading...
</div>
<div v-else>
{{ data }}
</div>
</template>
4. You can also use the experimental `<NuxtClientFallback>` component to handle SSR errors and provide fallback content:
```vue
<NuxtClientFallback>
<MyComponent />
<template #fallback>
<div>Loading...</div>
</template>
</NuxtClientFallback>
NuxtClientFallback documentation