0

Code Snapshot

In this code :

.then((movementItem) => {
                    if (!movementItem?.id) {
                        this.$router.back();
                    }

                    this.movement = { ...movementItem, accountName };

                    if (this.movement.comment) {
                        this.hasComment = true;
                    } else {
                        this.movement.comment = {
                            comment: '',
                            commentId: '',
                        };
                    }

                    this.$watch('movement.comment.comment', function(newVal, oldVal) {
                        console.log(newVal);
                        console.log(oldVal);
                    });
                })

If the "movement" has a comment, the watcher works as I expect, but if the "movement" does not have a comment, then I add an empty comment but the watcher is not working in that case, I've tried a lot of things ( Set the watcher at the Vue isntance, with computed properties etc ) but I can't figure out how make this code work.

Also I tried to set an example String in comment instead of an empty String but no success...

Obviously I have a input field where I can change my comment binded with v-model to "movement.comment.comment"

Can anyone explain why?

I included an image in case you want to see the code with bracket pairing.

EDIT:

Turns out that I can't add a reactive property to a data object in Vue which has been instantiated before. The reactivity is a must for a watch to work properly so...

https://v2.vuejs.org/v2/guide/reactivity.html#For-Objects

I just need to use something like:

this.$set(this.someDataObject, 'newProperty', 'initial value')

With this you just added the property 'newProperty' to the object in data.

tony19
  • 125,647
  • 18
  • 229
  • 307
Daniel
  • 1
  • 1
  • You really shouldn't be adding a watcher inside a promise resolution callback... can you create a [mcve] to demonstrate your issue? – Terry Jan 24 '22 at 14:09
  • 1
    you should set up a deep watch on `movement` like the answer in this: https://stackoverflow.com/questions/41135188/vue-deep-watching-an-array-of-objects-and-calculating-the-change – Pete Jan 24 '22 at 14:12

0 Answers0