Toto Briac
Toto Briac

Reputation: 936

Vue.js Watcher on a storeState data

In my Vue.js I have a function that get labels from a picture using Google Vision. This function is inside a mixin so my code is not so bloated.

I then store the labels as an array in a storeState so I can access it in other components.

What I want is to call another function as soon as my array is stored. So I implemented a watcher:

watch: {
    this.storeState.labels: function () {
      anotheFunction()
      } 
    } 

But I get a Unexpected keyword 'this' error. So how can I trigger another function as soon as my this.storeState.labels is updated?

Upvotes: 2

Views: 523

Answers (3)

Mehmet Pekcan
Mehmet Pekcan

Reputation: 288

You have 2 way to do that. First using quotes syntax.

watch: {
  'storeState.labels'() {
     // Do your magic here..
  }
}

and second way is that watch the object deeply.

watch: {
  storeState: {
     deep: true,
     handler() {
       // Do your magic here
       // This way watches all your object changes so then while using this be sure that you're doing right magic
     }
  }
}

In addition, both case you should have a computed value to use storeState object in Vue side.

Upvotes: 0

Faran Ali
Faran Ali

Reputation: 482

You ahve to create a computed property first, and then watch that computed property to perform your operations upon changing

computed:{
    labels(){
       return this.storeState.labels; // did you mean return this.$store.state.labels ?
    }
},

watch:{
    labels:{
       handler:function(){
                anotherFunction()     
               }
        
    }
}

Upvotes: 0

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

Watch that property without using this keyword :

watch: {
    "storeState.labels": function () {
      anotheFunction()
      } 
    } 

Upvotes: 2

Related Questions