Reputation: 18563
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
Reputation: 109
As I understand your question:
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
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
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