When my Vue component is loaded, it fetches some data from server and place it in the component data:
JavaScript
x
11
11
1
data: function(){
2
return {
3
data: null,
4
dataChanged: false,
5
}
6
},
7
created: function(){
8
// fetch data from server
9
this.data = server_data
10
}
11
Now I want to watch for its changes, and set a bool dataChanged
when it’s changed:
JavaScript
1
6
1
watch: {
2
data: function(oldVal, newVal) {
3
this.dataChanged = true
4
}
5
}
6
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:
JavaScript
1
8
1
created: function(){
2
// fetch data from server
3
this.data = server_data
4
this.dataChanged = false
5
}
6
7
8
Advertisement
Answer
you can try if the value of data
is null
then it’s false;
JavaScript
1
7
1
watch: {
2
data: function(oldVal, newVal) {
3
if (this.data == null) this.dataChanged = false
4
else this.dataChanged = true
5
}
6
}
7