1

At the moment I have an object of data that is returned from my server that is bound to a series of inputs using v-model. What I'm attempting to do is determine if any updates to that object that was returned from the server have been made.

On created() lifecycle I make a GET request to the API for server data and then save that as data() on the component:

data() {
 return {
   user: {
    name: 'Marcus'
   }
 }
}

I then have a input inside of the component that utilizes v-model to bind the value:

<input type="text" id="name" v-model="user.name" />

What I'd like to do is be able to tell if user.name or any other key/value pairs that might be returned from the server within the user object have been changed.

I've created an example fiddle here.

Attempt 1

My first thought was to create some sort of comparison in that when I set the user object in the success from my GET request to go ahead and create a "default" object to then compare against:

const hasEdits = JSON.stringify(this.default.user) === JSON.stringify(this.user)

However, it appears that v-model will also change both user.name as well as default.user.name when any updates are made to the input field.

Thoughts

  • How could I compare these two objects without v-model updating both instances?
  • I'd like to be able to create some sort of method that would allow me to dynamically create an "edited" type object but when I have nested key/value pairs I don't understand how to first create the necessary structure within a new edited object as it returns undefined. If I were able to get around this, I could just test if edited object is true and then use spread operators to merge data before send with the original returned object.
ajames
  • 113
  • 4
  • You are assigning your saved and editable objects to the same object. [You need to make a new copy](https://jsfiddle.net/vqgu9L6n/). `Object.assign` will only get you so far though if you have nested objects (properties of your object that are objects themselves), in which case you will need some other method to deep clone your object. – Bert Aug 14 '18 at 16:35

1 Answers1

1

To separate the backup copy and the edited copy, you can clone the object returned from the server(taken from your fiddle):

created() {
    const serverObj = { name: "Marcus" };
    this.user = serverObj;
    this.saved.user = JSON.parse(JSON.stringify(serverObj)); 
}

That will create a new object for the backup data so the v-model bindings do not affect it. I'm not sure comparing them by serializing both to JSON is stable. You might want to look here for alternative deep comparison methods.

user3357118
  • 844
  • 7
  • 14
  • 1
    Ah yup. Figured it was something as simple as that but hadn't thought of it. Thanks a bunch. – ajames Aug 14 '18 at 16:51