JavaScript data storage and copy depth practical application

JavaScript are two data types.
1. Simple data types are: number, string, boolean, undefined and null
when declare a simple data types of variables, data in memory will present the stack.
2. The complex data types. Object

var student = new Person

  

When I create an instance of time, will open up a space in memory, objects stored on the heap, student is a memory address, pointing to objects in the heap.

Deep and shallow copy copy problem is created when storing complex data.

Shallow copy what I just get into the memory address of the object, can point to the original object. When I modified the original object will change.
Deep copy is to re-create a space object in the heap, I modified the original object does not affect the object of my newly created.

In fact in the development process, we encountered a problem, is about the depth of copies.

First, some background development. It is a project management background. After the data table have edit page, edit the page and add pages taking advantage of the traditional values vue father and son, when I was added to the parent component sub-assembly is an empty object, when I was editing, incoming current table row data to the sub-assembly in the form of objects.
The method subassembly.

 // 打开弹窗
    dialogOpen() {
      console.log('打开页面',this.expert)
      this.$refs.form.resetFields();
      if (this.expert.id) {
        // 进入修改
         this.form = this.expert
      } else {
        this.form = {};
      }
    },

  By expert.id determine whether the page is added, and if so, the expert in content to pass the current form, if not, empty the contents of the form.

props: {
    expert: Object,
    value: Boolean
  },

  

The component values ​​received

The problem is this: When I open the Edit pop, did not do any of the current list of data changes and close the page, list page becomes empty.

The reason: When I enter the edit page, this.form = this.expert is shallow copy, copy the address of the object. When I click Add, to the parent component this.expert = {}, at this time, this.form is empty, then click Edit, form is empty of.

After the resolution code

 // 打开弹窗
    dialogOpen() {
      console.log('打开页面',this.expert)
      this.$refs.form.resetFields();
      if (this.expert.id) {
        // 进入修改
         this.form = {...this.expert}// 深拷贝
      } else {
        this.form = {};
      }
    },

  

Reproduced in: https: //www.cnblogs.com/JiAyInNnNn/p/11053009.html

Guess you like

Origin blog.csdn.net/weixin_34414650/article/details/93543327