vue snippet

Vue.js Snippets – Display Loader while Fetching Content


When loading data in Vue.js applications, you may want to display some form of loading indicator so your users will know that something is happening. Vue.js provides us with the v-if directive which allows us to conditionally show/hide any piece of markup.

In the snippet below, we have our data property loading which is set to false by default. Before we start fetching our data, we set loading to true and when we get a response from the server, we set it back to false.

<template>
  <main>
    <div v-if="loading" class="loader"></div>
    <div>{{ todo }}</div>
  </main>
</template>

<script>
export default {
  data() {
    return {
      loading: false,
      todo: ''
    };
  },
  async created () {
    this.loading = true
    try {
      const res = await fetch('https://jsonplaceholder.typicode.com/todos/1')
      this.todo = await res.json()
      this.loading = false
    } catch (error) {
      console.log(error)
      this.loading = false
    }
  }
};
</script>

<style lang="scss" scoped>
.loader {
  border: 16px solid #f3f3f3;
  border-top: 16px solid #3498db;
  border-radius: 50%;
  width: 36px;
  height: 36px;
  animation: spin 2s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>

Our loader is a simple spinner styled with CSS. If loading is true, the spinner is displayed else it’s hidden. We can apply the same technique with progress bars as well.

Use Cases

  • Fetching a list of users
  • Fetching an image/video

Share on social media

//