I mainly use watched variables for loading asynchronous data, and right now every time I do this I end up with something like this which really doesn't follow the DRY principle.
watch:{
foo(nv,ov){
//Make some async call based on nv
}
},
created(){
//Make some async call based on foo
}
So I propose that, unlike the current implementation, watched variables run when the state is first initialized. This would be a breaking change, but unlike the way it works currently there is an easy way of choosing whether to run the watch function at creation or not. Since watch functions have two parameters, the new value and the old one, it should be possible to pass in null
or undefined
for the old value. Then component authors if they don't want to run the watch function at component creation can merely check first to see if the the value is switching from a null
or undefined
value.
Watched variables would run when the component is created. So you could have only.
watch:{
foo(nv,ov){
//Make some async call based on nv
}
}
I imagine that in a number of cases if a watch function runs one extra time it wouldn't be a problem, but if for some reason it is unwanted then you could have
watch:{
foo(nv,ov){
if(ov===null)return;
//Make some async call based on nv
}
}
you can simply do this:
watch: {
foo: {
immediate: true,
handler(nv, ov) { ... }
}
}
Thank you I had read through the guide and had glanced through聽https://vuejs.org/v2/api/#watch. I didn't realize聽https://vuejs.org/v2/api/#vm-watch had further information. This can be closed.
Most helpful comment
you can simply do this:
https://vuejs.org/v2/api/#vm-watch