Vue: Have watch functions run on component creation similar to computed variables.

Created on 9 Apr 2017  路  2Comments  路  Source: vuejs/vue

What problem does this feature solve?

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.

What does the proposed API look like?

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

Most helpful comment

you can simply do this:

watch: {
  foo: {
    immediate: true,
    handler(nv, ov) { ... }
  }
}

https://vuejs.org/v2/api/#vm-watch

All 2 comments

you can simply do this:

watch: {
  foo: {
    immediate: true,
    handler(nv, ov) { ... }
  }
}

https://vuejs.org/v2/api/#vm-watch

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.

Was this page helpful?
0 / 5 - 0 ratings