#Loading with LazyComponent

4 messages · Page 1 of 1 (latest)

fresh cosmos
#

There is a way to use this vue code?
<Suspense>
<template #default>
<RouterView />
</template>
<template #fallback>
<div>
<h1>Loading....</h1>
</div>
</template>
</Suspense>

final yewBOT
#

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>

NuxtPage documentation

If you want to show a loading state while your components or pages are loading, you have several options:

  1. Use <NuxtLoadingIndicator> for page navigation loading:
<template>
  <div>
    <NuxtLoadingIndicator />
    <NuxtPage />
  </div>
</template>
  1. For lazy-loaded components, you can use the defineAsyncComponent with 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.

  1. 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

These approaches are more aligned with Nuxt's architecture than manually implementing Suspense with RouterView.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: