How to create a Pre-Loading/ Splash Screen in Nuxt.js before the app starts?

3.7k views Asked by At

I have tried to add a loader as shown in the nuxt.js documentation in between the routes but its not work. But I'm not able to add a splash screen before the app starts.

Code snippet in my components/loading.vue

<template>
  <div v-if="loading" class="loading-page">
    <p>Loading...</p>
  </div>
</template>

<script>
export default {
  data: () => ({
    loading: false
  }),
  methods: {
    start(){
      this.loading = true
    },
    finish(){
      this.loading = false
    }
  }
}
</script>

In nuxt.js.config

export default {
...

loading: '~/components/loading.vue'
...
}
1

There are 1 answers

1
Tarkan On

As far as I know, you can't use a Vue component as a loading indicator for your your Nuxt app.
You will have to create an HTML document instead. This HTML document does not have to have an <html>, <head> or <body>. It just has to be the splash screen you want to show.

Here's how I did it:

  1. Create an html document ~/assets/loading.html
  2. Add the following to nuxt.config.js file.
loadingIndicator: {
  name: '~/assets/loading.html'
}
  1. Save and reload your page, you should now have a custom loading indicator / splash screen.

Example HTML file:
Here's a very simple file to show a splash screen image, when loading a nuxt app.

<div style="height: 100vh; width: 100vw; display: flex; align-items: center; justify-content: center; flex-direction: column; background-color: #004066; margin-left: -8px; margin-top: -8px; overflow: hidden;">
  <img width="90%" src="<%= options.img %>">
</div>

NOTE:
Pay attention to <%= options.img %>. I'm making use of options, which can be defined in the nuxt.config.js simply by adding more keys to loadingIndicator, an example can be seen below.

loadingIndicator: {
  name: '~/assets/loading.html',
  img: '/loading.gif'
}

NOTE 2:
When accessing assets such as images in the loading indicator, you will have to put them in the /static folder.

Documentation: https://nuxtjs.org/docs/2.x/features/loading#custom-indicators
Official examples: https://github.com/nuxt/nuxt.js/tree/dev/packages/vue-app/template/views/loading