Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 365
iainc123 Avatar asked Nov 07 '18 11:11

iainc123


People also ask

Can I watch a computed property in 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 .

How does watch work in Vue?

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.

Can I watch a computed value?

Yes, you can setup watcher on computed property, see the fiddle.

How do you trigger a watch in Vue?

To trigger the Vue watch method, you should assign a new city name to the value property of the ref object.


1 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)
  }
}
like image 97
artoju Avatar answered Sep 30 '22 04:09

artoju