I have a data variable that is of boolean type, and I have included this in a watch hook. When the value changes to true
, I execute certain tasks within the watch function and everything works perfectly.
watch: {`
` boolVar: function (val) {`
` if(val === true){`
` //performing some tasks`
` }`
` }`
`}`
`
`
`Later, I needed to add additional functionality where I had to toggle the variable if it was already set to true
in order to re-trigger the watcher. If at a certain point, boolVar
is already true
and I need the watcher to run again, what would be the best approach?
Initially, I tried toggling the boolVar
like this:
//inside another function`
`if(this.boolVar === true){`
` this.boolVar = false;`
` this.boolVar = true;`
`}`
`
`
`However, this approach did not work as expected. After some experimentation, I discovered that there was a difference in the time delay at which the watcher was listening, causing the code to not function as intended.
` `I then implemented a different method using the sleep function and promises to introduce a 1 millisecond delay so that the watcher could listen properly, and it worked according to my requirements:
` `//inside another function`
`//making the function 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 a better approach to handle this scenario, where you need to toggle a variable being watched and re-run tasks? While my current workaround is functional, I believe the watcher should inherently detect when the same variable is toggled (which it currently does not).
` `