Object.assign

handleCancel (val) {
      Object.assign(this.modalFormData, val)
      // this.modalFormData = val
    }

is there any difference between these two assignments in vue?
there is a problem with writing that way below, and it may also be affected by other places, but it is correct to write like that above. Why?

Apr.08,2021

The purpose of

Object.assign is that copying all the attributes in val to this.modalFormData, is not the same as assigning the entire val to this.modalFormData.
for example, please compare by yourself

 

look at MDN

  1. for deep copies, you need to use other methods because Object.assign () copies attribute values. If the property value of the source object is a reference to the object, it only copies that reference value.
  2. if the attribute in the target object has the same key, the attribute will be overridden by the attribute in the source. The properties of later sources will similarly override the previous properties.

so it can do three things

  1. Deep copy of shallow layer
  2. merge objects
  3. merge values with the same attributes
Menu