Skip to content
Advertisement

How to watch for data changes in VueJS after data is loaded from server?

When my Vue component is loaded, it fetches some data from server and place it in the component data:

 data: function(){
    return {
        data: null,
        dataChanged: false,
    }
 },
 created: function(){
     // fetch data from server
      this.data = server_data
 }

Now I want to watch for its changes, and set a bool dataChanged when it’s changed:

watch: {
   data: function(oldVal, newVal) {
       this.dataChanged = true
   }
}

The problem is, when data is initially loaded in created, it also triggers the watcher.

How do I watch for changes AFTER its initialization?

I have tried resetting dataChanged to false right after initialization, it doesn’t work:

created: function(){
     // fetch data from server
     this.data = server_data
     this.dataChanged = false
}

 

Advertisement

Answer

you can try if the value of data is null then it’s false;

watch: {
  data: function(oldVal, newVal) {
    if (this.data == null) this.dataChanged = false
    else this.dataChanged = true
  }
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement