Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue JS watcher not working

Tags:

vue.js

vuejs2

I am working on a component right now that has a prop called item that I need to watch for changes. I have a watch like this so far:

watch:{
   item(newVal, oldVal) { // watch it
     console.log('Prop changed: ', newVal, ' | was: ', oldVal)
   }
}

The item gets an update on a button click with a new timestamp. In the Vue dev tools, I can see that the prop is being updated with the value, but the watcher is not working and I am not even getting a log message.

like image 651
John Doe Avatar asked Jun 13 '18 15:06

John Doe


2 Answers

As @Bert says if item is an object and what changes is one of its props, your watcher is not going to be triggered.

Could you try this:

watch:{
   item:{
      handler: function(newVal, oldVal) { // watch it
        console.log('Prop changed: ', newVal, ' | was: ', oldVal)
      },
      deep: true
   }
}
like image 107
Luby Shandra Avatar answered Sep 28 '22 14:09

Luby Shandra


This is a little bit off subject because it involves my data structure, but still presented me a problem with the data was not being watched. I use .Net with vuejs CDN link and a complex data structure. VueJs does not like that structure for watch. So for the data item "watchme", watch doesn't work using this -> object.item.watchme nor using watchme. So I had to do the following:

I first need to set up a surrogate under computed

computed:
watchme: function () {
     return object.item.watchme;
 },

then watch the surrogate

watch:

watchme: {
          handler: function (newVal, oldVal) { // watch it
          console.log('prop changed: ', newVal, ' | was: ', oldVal)
          },
          deep: true
    }

For me this worked:

like image 42
Clarence Avatar answered Sep 28 '22 13:09

Clarence