[Vuejs]-VueJS- prop is being mutated when local copy updates

0👍

This happens because in Javascript, object is passed by reference. When you do user : this.account.user, you are passing the object reference to user data. That’s why when you edit user data, account.user gets edited as well, they refer to the same object.

You can clone it using ES6 spread operator.

return { user : {...this.account.user} }

If you are not using ES6, i would suggest you to use lodash clone instead.

return { user : _.clone(this.account.user) }

(Btw, the cloning methods above only works for shallow object. For deeply nested object, use lodash cloneDeep instead.)

Leave a comment