1

I know I can 'watch' particular properties in my data changing in vue, but is it possible to handle any part of my component's data changing?

For example, I have:

data() {
   return {
     myProp: false,
     myOtherProp: true
   }
}

I can add a watch like so:

 watch: {
    "myProp": function(val, oldVal) {
      // Do something
    }
}

And could add one for myOtherProp too, but in reality I have many many properties, how do I add one handler for all?

Further Context

The end-goal here is to detect a 'dirty' state so I can determine whether to warn the user they're potentially going to lose unsaved changes or not.

What I've Tried

I know I could probably combine all my properties in data into one type, and just watch that, but it's too disruptive a change at the moment, too much risk. I'm intrigued into whether a global handler is possible anyway.

1 Answer 1

2

Easiest way to do this is to make a computed property, when this property changed you can call your function:

computed: {
    hash () {
      return `${this.myProp}
          |${this.myOtherProp}
   }
},
watch: {
   "hash": function(val, oldVal) {
      // Do something
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Very clever! I like it. Thanks.
Also, if myProp is an object with nested properties, you can return JSON.stringify(this.myProp) in the hash function and compare against that in the watch function.

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.