Skip to content

Mohcin Bounouara

Thoughts about software engineering and life

Vue.js: Implementing a Loading Spinner in Your Project

Introduction:

Learning a new JavaScript framework can be both exciting and challenging. Two years ago, I embarked on a journey to master Vue.js, but like many others, I often found myself procrastinating and only touching it from time to time. 

However, this month, I decided to take my Vue.js learning journey seriously. I dedicated myself to studying both the theory and practice, and I also took the opportunity to refresh my JavaScript knowledge. To put my learning to the test, I started a simple project in which I aimed to implement everything I had learned. In this blog post, I’ll guide you through one of the features I implemented: a loading spinner that appears while waiting for data to load. Please note that the feature explanation provided here is simplified, and the actual project contains many more components.

Implementing a Loading Spinner:

Let’s dive into the code and concepts behind creating a loading spinner in Vue.js. Imagine you have a list of names that you want to render, but you want to display a “loading spinner” for 5 seconds after initiating the data fetch. Here’s how you can achieve this:

<template>
  <div>
    <div v-if="loading">Loading...</div>
    <ul v-else>
      <li v-for="(item, index) in list" :key="item.name">
        {{ item.name }} - {{ item.age }}
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      loading: true, // Initially set to true to show loading message
      list: [{name: 'Mohcin',age: 30}, {name: 'ali',age: 27}] // Your data list
    };
  },
  mounted() {
    // wait for a 5-second delay before showing the list
    // we put it into mounted to make sure we can use it in any place of our projects
    setTimeout(() => {
      this.loading = false; // Set loading to false to display the list
      // You can load your list data here if it's an asynchronous operation
    }, 5000);
  }
};
</script>

Explanation:

In this example, we create an initial state where the loading variable is set to true, and a loading message is displayed. After a 5-second delay, which we simulate using setTimeout (if we have real data then we will wait until data is fetched from the API for example), the loading variable is set to false, and the list is displayed.

Conclusion:

Learning Vue.js is my current goal, so I’m putting some pressure on me with posting about it in my blog.. Happy coding!