Vue JS - how does watching a computed trigger it when a field used within it updates?

Viewed 8047

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.

2 Answers

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

Does this help?

However, the difference is that computed properties are cached based on their dependencies. A computed property will only re-evaluate when some of its dependencies have changed.

From documentation: https://v2.vuejs.org/v2/guide/computed.html

From my experience it does re-evaluate when a property used inside changes as long as the watcher returns a value, it checks if the value changes.

Related