NeoWang
NeoWang

Reputation: 18563

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
}

 

Upvotes: 1

Views: 2583

Answers (3)

chen7david
chen7david

Reputation: 109

As I understand your question:

  • Problem: The watcher function gets called when data is initially loaded.
  • Objective: Ignore initial change (when data is initially loaded) but run on all subsequent changes.
  • Solution: Use a flag in your async operation.

Example:

data: {
  items:[],
  isDoneLoading: false
},
watch: {
  items(){
    if(!this.isDoneLoading) return
    // runs only after data is done loading.
  }
},
methods: {
  async loadItems(){
     const { data } = await this.$http.get('/examples')
     this.items = data
     const setFlag = () => this.isDoneLoading = true
     await setFlag()
  }
},
mounted(){
  this.loadItems()
}

Upvotes: 1

sazzad
sazzad

Reputation: 525

you can change dataChanged in the watcher like this

watch: {
  data(newValue, oldValue) {
   if(oldValue !== newValue) 
    this.dataChanged = true;
   else
    this.dataChanged = false; 
 }
}

Upvotes: 1

tuhin47
tuhin47

Reputation: 6068

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
  }
}

Upvotes: 1

Related Questions