Search code examples
vue.jscomputed-properties

Vue JS: Computed value vs. watcher


I have 3 Booleans at the start, and if one of these 3 values changes by the user (e.g. HTML checkboxes), I want to set changed = true.

data()
  return {
    boolean1:false, //may initally be true/false
    boolean2:true,  //may initally be true/false
    boolean3:false, //may initally be true/false
    changed: false  //no changes to start with
  };
},

How do I track these 3 values properly in Vue? My impulse would be to use a watcher, but I now read several times that a computed property is the better choice for such tasks. Unfortunately, they didn't provide examples for such a simple tracking task, so how would a computed property look like? So far I have this:

computed: {
  comp_settings_change: function(){
    // if booleans change, set to true, else stay at false.
    return true
  }
},

Solution

  • A watcher is more appropriate than a computed prop in this case because the flag only needs to be set once.

    You could use vm.$watch() on the Booleans, which returns a function to stop watching after the initial change, allowing you to create a one-shot callback:

    export default {
      mounted() {
        const unwatch = this.$watch(
          () => [this.boolean1, this.boolean2, this.boolean3],
          value => {
            unwatch()
            this.changed = true
          }
        )
      },
    }
    

    demo