0

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
  }
},
2
  • 1
    Your impulse is right, a watch is better because you only want to set a flag when an event fires Commented Dec 8, 2020 at 23:56
  • 1
    really depends on what you are trying to do, if you are just trying to detect if the booleans have changed from the initial state, then a computed would be simple, but you need to capture the initial state, that way if a boolean changes from false to true, then changed would be true, then if that boolean changes back to false, then changed would go back to false. Commented Dec 9, 2020 at 0:09

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

Great answer, thanks. So if I would wanted to watch the booleans constantly (not just set the flag once but on every change) I would use a computed value with this $watch function?
Come to think of it, a computed property with $watch() would probably just be a watcher :)
If you wanted to set the flag with every change to the Booleans, you could use the same solution but without unwatch().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.