Record methods that vue cannot detect array and object changes.

Keywords: Javascript Vue

Test data:

  items: [
    {name: 'Business status', id: 'taskState', data: [{name:'whole', id: 0},{name:'Have in hand', id: 1},{name:'Completed', id: 2},{name:'Filed', id: 3},{name:'Terminated', id: 4}]},
    {name: 'Business status', id: 'taskState', data: [{name:'whole', id: 0},{name:'Have in hand', id: 1},{name:'Completed', id: 2},{name:'Filed', id: 3},{name:'Terminated', id: 4}]},
    {name: 'Business status', id: 'taskState', data: [{name:'whole', id: 0},{name:'Have in hand', id: 1},{name:'Completed', id: 2},{name:'Filed', id: 3},{name:'Terminated', id: 4}]},
    {name: 'Business status', id: 'taskState', data: [{name:'whole', id: 0},{name:'Have in hand', id: 1},{name:'Completed', id: 2},{name:'Filed', id: 3},{name:'Terminated', id: 4}]},
  ]

Difficulties:

  1. items is an array, which is nested with many layers of objects. Of course, the data is not the same. I'm just illustrating here.
  2. There are two difficulties in this. First, directly changing the number of items, vue can not detect. Second, add the object properties in items[i]. vue is also not detected.
  3. Of course, according to the official documents of vue, the main problem that can't be detected is caused by JavaScript. (Yuxi, you're right)

Code:

// Solution    
this.$set(this.items, 0, Object.assign({}, this.items[0], { active: 0, defaultActive: 0 }))

// practical application
this.items.forEach((r, row) => { // Array of variables with default values for each object
    this.$set(this.items, row, Object.assign({}, this.items[row], {
      thisActive: r.thisActive ? r.thisActive : 0,
      defaultActive: r.defaultActive ? r.defaultActive : 0,
      data: r.data ? r.data : [],
      pageIndex: r.pageIndex ? r.pageIndex : 1,
      pageSize: r.pageSize ? r.pageSize : 20,
      options: r.options ? r.options : {scrollbar: true, pullUpLoad: true},
      ref: r.ref ? r.ref : 'scroll' + row
    }))
})

Here is an explanation. The following code is to solve the problem that objects cannot be detected. Here is a way to add multiple attributes at once.

let test = Object.assign({}, this.items[0], { active: 0, defaultActive: 0 })

The following code is to solve the problem that array cannot be detected. (objects can also use this method)
Index -- the index 'age'|| 13 represents the key value in the object respectively

this.$set(this.items, index, test)) // Array method
this.$set(this.items[index], 'age', 13)) // Object method

The above solution code is from the official document of vue Link description , if you don't understand, you can type according to the document.

Posted by sectachrome on Wed, 04 Dec 2019 07:56:43 -0800