search

Home  >  Q&A  >  body text

Adding a page loader to your Nuxt 3 application: a step-by-step guide

I'm building an application using Nuxt 3 and I want to add a page loader until the website loads.

P粉014218124P粉014218124400 days ago756

reply all(1)I'll reply

  • P粉436688931

    P粉4366889312023-10-26 00:08:21

    Based on this article. There is a simple but limited solution and a fully customized solution.

    built-in

    Contains a loading progress bar that can be used like this

    <template>
      <NuxtLayout>
        <NuxtLoadingIndicator />
        <NuxtPage />
      <NuxtLayout>
    </template>
    

    But it only has a predefined UI and can only be customized using these attributes

    • Color: The color of the loading bar.
    • Height: Height of the loading bar in pixels (default is 3).
    • Duration: The duration of the loading bar in milliseconds (default is 2000).
    • Limit: Limit showing and hiding in milliseconds (default 200).

    Customizable loader

    If you need a custom loader (such as a full screen spinner with a background), a different approach is required. This approach allows you to create any loader and display it when needed.

    <template>
      <div class="h-screen">
        <div v-if="loading" class="fixed left-0 top-0 h-0.5 w-full z-50 bg-green-500" />
    
        <NuxtLayout>
          <NuxtPage />
        </NuxtLayout>
      </div>
    </template>
    
    <script setup lang="ts">
      const nuxtApp = useNuxtApp();
      const loading = ref(false);
      nuxtApp.hook("page:start", () => {
        loading.value = true;
      });
      nuxtApp.hook("page:finish", () => {
        loading.value = false;
      });
    </script>
    

    Nuxt3 provides application runtime hooks with interceptors for page:start and page:finish events. To use them correctly you need to use these hooks (in app.vue or your custom component) this way:

    reply
    0
  • Cancelreply