qecce
qecce

Reputation: 71

Vue perform long lasting task on button click

I dont understand the right way to handle long lasting tasks/calls when binding a vue method to a Ui button click event.

I expect the following:

But instead the button click animation and button beeing disabled appears after the execution of the long task.

What do I miss? Is it Vue specific or just JS?

Thank you very much.

File Test.vue:

<template>
    <div>
      <button  v-on:click="buttonClicked" :disabled="loading">My Button</button>
    </div>
</template>

<script>

export default {
    data() {
        return {
          loading: false,
        };
    },
    methods: {

      buttonClicked(){
        if(!this.loading){
          this.loading = true;
          this.doSomeTask()
        }
      },

      doSomeTask(){
        console.log("task started");
        for (let i= 0; i < 1000000000; i++){
          if(i % 10000000 === 0){
            console.log(i)
          }
        }
        console.log("task over");
        //this.myLoad = false;
      }
    },
};
</script>

Upvotes: 0

Views: 663

Answers (2)

Gurkan Ugurlu
Gurkan Ugurlu

Reputation: 467

Because javascript is a single threaded programming language. You can do one thing at the time in javascript. Because of that if you have high computed functions browser could be unreachable. You need to use backend for functions like this.

Upvotes: 1

hassan-pudineh
hassan-pudineh

Reputation: 82

It should work for you:

export default {
  data() {
    return {
      loading: false,
    };
  },
  methods: {

    buttonClicked() {
      if (this.loading) return;
      this.loading = true;
      this.doSomeTask();
    },

    doSomeTask() {
      console.log("task started");
      for (let i = 0; i < 1000000000; i++) {
        if (i % 10000000 === 0) {
          console.log(i)
        }
      }
      console.log("task over");
      //this.myLoad = false;
    }
  },
};
<template>
    <div>
      <button @click="buttonClicked">
           <loading-icon v-if="loading"></loading-icon>
           <span v-else> Your Button</span>
      </button>
    </div>
</template>

Upvotes: 0

Related Questions