I have a computed field which sets a data property called 'completed', based on whether a text field has been filled out within a questionnaire:
setCompleted: function () {
this.completed = this.required && this.textAnswer !== '';
},
This computed is not referenced in my html and is solely used to set the completed property. The only property which can change due user input is textAnswer, bound as the model on a text input.
I have an empty watcher set to watch this computed field like so:
setCompleted: function () {
},
With the watch set, this works and setCompleted updates, but without the watch, setCompleted does not get hit when debugging and completed does not get updated at all.
My question is this - how does watching the computed make it update when a field used within it updates? With the watch set does Vue watch every property inside the computed for change and then run the computed when one changes?
Note - I know I can refactor this into watching textAnswer and calling a method from that watch to update completed, but I want to know how this code actually works and if it is bad practice or actually something that was intended to be allowed with Vue.
The computed property is another option that is part of the options API, and in Vue 2, it sits at the same level as methods , data , watch , and lifecycle methods like mounted .
A watcher in Vue is a special feature that allows us to observe some data and perform specific actions when it changes. It is a more generic way to observe and react to data changes in the Vue instance.
Yes, you can setup watcher on computed property, see the fiddle.
To trigger the Vue watch method, you should assign a new city name to the value property of the ref object.
I think the practice for computed properties is to return a value, which the watcher can watch. In this case completed would be the computed value.
computed: {
completed: function () {
return this.required && this.textAnswer !== '';
},
},
watch: {
completed: function(val) {
console.log(val)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With