The problem of vue object assignment

the following is a copy of the official document, but I haven"t figured out the difference between the two methods

sometimes you may need to assign multiple new properties to existing objects, such as using Object.assign () or _ .extend (). In this case, you should create a new object with the properties of both objects. So, if you want to add new responsive attributes, don"t go like this:

Object.assign (vm.userProfile, {
age: 27,
favoriteColor: "Vue Green"
})

you should do this:

vm.userProfile = Object.assign ({}, vm.userProfile, {
age: 27,
favoriteColor: "Vue Green"
})

Feb.09,2022

means don't overwrite the old one in order to create a new object.
see the following example

var arr=[1];
arr.splice(0,1); //[] 
arr.concat(2);   //[1] ,

Let's start with the difference.

let a = {};
const b = a;
Object.assign(a, { name: 1 });
console.log(a, b); // { name: 1} { name: 1 }
a = Object.assign({}, a, { age: 10 });
console.log(a, b); // { name: 1, age: 10} { name: 1 }

you can see that a and b use the same object, while in the latter case, a points to a new object (reassign).

of course, the a here is vm.. UserProfile

then you can learn a little bit about the bi-directional binding mechanism of vue , such as .

then you will know that the current vue bidirectional binding is based on Object.defineProperty , where Object is vm .

Let's take a look at the two writing methods. The former is just vm.. One of the values in userProfile has changed without triggering setter , which gives vm. UserProfile has a new value that triggers setter . So vue recommends the latter.

Menu