DEV Community

Gishan Chaminga Abeysinghe
Gishan Chaminga Abeysinghe

Posted on

How to show loading when changing pages in Nuxt3

I am showing here how to make loading screen when changing pages, there should be asynchronous calls with await to make it show in this method.

export default defineNuxtPlugin((nuxtApp) => {
  const global = useGlobalLoading()

  nuxtApp.hook('page:start', () => {
    global.showLoading()
  });
  nuxtApp.hook('page:loading:end', () => {
    global.hideLoading()
  });
})

Enter fullscreen mode Exit fullscreen mode
export function useGlobalLoading() {
  const isGlobalLoading = useState('global-loading', () => false)

  function showLoading() {
    isGlobalLoading.value = true
  }

  function hideLoading() {
    isGlobalLoading.value = false
  }

  return {
    isGlobalLoading,
    showLoading,
    hideLoading,
  }
}
Enter fullscreen mode Exit fullscreen mode

In your app.vue

<script setup lang="ts">
import Loading from './components/Loading.vue'

const globalLoading = useGlobalLoading()
</script>

<template>
  <div class="h-screen w-full flex justify-center items-center relative">
    <div
      v-show="globalLoading.isGlobalLoading.value"
      class="h-full w-full flex justify-center items-center fixed bg-gray-400/50 z-[9999]"
    >
      <Loading />
    </div>
    <div class="h-full w-full">
      <NuxtLayout>
        <NuxtPage />
      </NuxtLayout>
    </div>
  </div>
</template>

Enter fullscreen mode Exit fullscreen mode

Top comments (0)