Skip to content
Advertisement

toggle the value of variable that is being watched in vuejs

I have a data variable whose typeof is boolean and I have put this in watch hook. On changing the value to true , I’m performing some tasks in watch like this and it’s working perfectly.

watch: {
   boolVar: function (val) {
     if(val === true){
       //doing some tasks
     }
   }
}

Then I started to integrate some other stuff and requirement is to toggle the variable in case if it’s already true because i want to perform the same tasks with watcher. Suppose, on a certain point boolVar is already true and I have to run the watcher again then what should I do?

Previously, I was toggling the boolVar like this

//in some other function
if(this.boolVar === true){
  this.boolVar = false;
  this.boolVar = true;
}

It was supposed to work as watcher will listen and perform the functionality in the watcher on value change when it’s true. But, It’s not working as I was expecting.

So, after some trials, I get to know that there is a difference/mismatch in time delay on which watcher is listening that is why my code was not working.

Then I tried this methodology (by using sleep and promise methodology so that after 1 Milli seconds watcher can listen) and It’s working again with my requirement.

//in some other function
//now function is async to use await

if(this.boolVar === true){
  this.boolVar = false;
  await this.sleep(1);
  this.boolVar = true;
}
//sleep function
sleep(ms) {
      return new Promise((resolve) => setTimeout(resolve, ms));
},

Is there any best approach to handle this? in case where you want to toggle the variable that is being watched and perform some tasks again? Because currently, my hack is working but I think watcher should detect when you toggle the same variable (as I was expecting but it’s not detecting)

Advertisement

Answer

You should use Vue.$nextTick.

if(this.boolVar === true){
  this.boolVar = false;
  this.$nextTick(() => {
    this.boolVar = true;
  })
}

If you don’t want to use $nextTick, you can do like that :

  watch: {
    boolVar: {
      handler(val) {
        console.log(val)
      },
      deep: true
    }
  }

However, why don’t you just make a doSomeWork() function, call it in your watcher, and when you need to re-execute that logic, you call the function rather than toggling your boolean? That would make more sense to me, but maybe I’m missing some details. :

watch: {
   boolVar: function (val) {
     if(val === true){
       this.doingSomeTasks()
     }
   }
}

And :

if(this.boolVar === true){
  this.doingSomeTasks()
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement