DEV Community

Cover image for Vue Quick Shot - Using a Loading Message
Raymond Camden
Raymond Camden

Posted on • Originally published at on

Vue Quick Shot - Using a Loading Message

Well, my grand plan to do one blog post per day of Vue quick tips failed rather quickly, but I can get two out today and get back on track. Honest, I can. While I wasn't planning on making every tip link to the previous one, my first two tips do exactly that.

My first tip explained how to disable a submit button while you waited for an Ajax call to finish. (Or any async call, and I actually used window.setTimeout instead of Ajax.) Today's tip builds on that by adding a rather simple, but helpful, modification - a loading message.

In the previous example, when you hit the submit button I disabled it while we waited for the result. You can see that in the CodePen below.

While the disabled button lets the user know something is going on, it would be nice to be a bit more obvious. First, let's add a new conditional div to the layout:

<div id="app" v-cloak>
  <form @submit.prevent="doSearch">
    <input type="search" v-model="term" placeholder="Search">
    <input type="submit" value="Perform Search" :disabled="searchDisabled">

  <div v-if="searching">
    <p><i>Please stand by, I'm searching...</i></p>

  <div v-if="result">
    <b>The result: </b>

Enter fullscreen mode Exit fullscreen mode

Right in the middle you can see a new condition, v-if="searching" and a message inside. You could also generate an Ajax loader if you want...

Ajax loader

I then tweaked my JavaScript a little bit:

Vue.config.productionTip = false;
Vue.config.devtools = false;

const app = new Vue({
  data: {
    async doSearch() {
     if(this.term === '') return; 
     console.log(`search for ${this.term}`);
     //disable the button
     this.searchDisabled = true;
     // clear previous result
     this.result = '';
     this.searching = true;
     this.result = await searchMyAPI(this.term);
     //re-enable the button
     this.searchDisabled = false;
     this.searching = false;

async function searchMyAPI(s) {
  return new Promise((resolve, reject) => {
    window.setTimeout(() => {
      resolve(`something for ${s}`);
    }, 3000);

Enter fullscreen mode Exit fullscreen mode

I added a default value for searching and within doSearch, I set it to true before the search and back to false after. Here's a CodePen you can test with:

That's it for this tip. I'll have the next one up later today, and hopefully, one more for Thursday and Friday. Enjoy!

Top comments (2)

tirtakeniten profile image
Tirta Keniten

Hi Raymond, nice article. I was using loading message nor animation to tell user that the data is still loading. But since I saw Facebook is using content placeholder, I started to experiment with it and it turned quite beautiful. This is the package Enjoy

raymondcamden profile image
Raymond Camden

That's dang nice!