Home » vue » is it possible to access variable in watch() function vue

is it possible to access variable in watch() function vue

Posted by: admin November 26, 2021 Leave a comment

Questions:

I want to access variable asd in my watch() function and clear asd interval I tried code below but it’s not working timer goes below 0 so any possible solutions?

  methods:{
    testing(){
        this.sTimer--;
      if(this.sTimer == 0){
        clearInterval(this.asd)
      }
    }
},
watch(){
 var asd = setInterval(() => this.testing(), 1000);
}
Answers:

Your watcher is not watching any thing! You need to provide an data item for which it watches for it’s changes

watch: {
  item: function (newItem, oldItem) {
    console.log(oldItem + " changed to: " + newItem);
  }
},

Also, you might want to add your asd variable to data section.

data() {
  return{
    asd = null;
  }
},
methods: {
    testing(){
        this.sTimer--;
      if(this.sTimer == 0){
        clearInterval(this.asd)
      }
    }
},
watch() {
 item: function (newItem, oldItem) {
   this.asd = setInterval(() => this.testing(), 1000);
 }
}