Skip to content
Advertisement

How to display an element in Vue component only after NProgress.done()

For displaying the loading status in a VueJS application I use the library NProgress. It works well and shows the loading bar and the spinning wheel. However the HTML content of the page is already rendered and displayed. I’d like to hide certain parts of the page while the request is running.

Is there any possibility to check programmatically for NProgress.done() and display the contents after it has been called?

I’d like something like this:

<template>
    <div>
        <NavBar />
        <div v-show="check here for NProgress.done()">
            <p>Here are all the nice things with placeholders for the data from the API.</p>
        </div>
    </div>
</template>

<script>
import NavBar from '@/components/NavBar';

export default {
    components: {
        NavBar
    }
}
</script>

The part “check here for NProgress.done()” is what I don’t know how to solve.

Advertisement

Answer

Looking through the documentation of NProgress, it looks like it exposes a “.status”, which returns the value of the current loader, but returns a “null” when the loader isn’t “started”.

<template>
  <div>
    <div v-show="state.status == null">
      <p>
        Here are all the nice things with placeholders for the data from the
        API.
      </p>
    </div>
  </div>
</template>
<script>
import Vue from "vue";
import NProgress from "nprogress";
import "nprogress/nprogress.css";

const state = Vue.observable(NProgress);

export default {
  data: () => ({ state }),
  mounted: function () {
    NProgress.start(); // Start the bar loading
    setTimeout(() => { // Perform your async workloads
      NProgress.done(); // .done() to finish the loading
    }, 5000);
  },
};
</script>

You’d need to make NProgress reactive, so you can just use Vue.observable(state).

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement