I'm building an application using Nuxt 3 and I want to add a page loader until the website loads.
P粉4366889312023-10-26 00:08:21
Based on this article. There is a simple but limited solution and a fully customized solution.
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
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: