[Vue | hole mending | 22] vue2 monitoring data principle (array)

Time:2022-4-28

Mentioned aboveObject.definePropertyUnable to monitor array changes, how does Vue solve this problem?

1. Principle

fromVue2 monitoring data change principleAccording to this article,Object.definePropertyThere are two defects:

  • The addition and deletion of object properties cannot be monitored
  • Unable to monitor array data changes

2. Sample code

  that is, directBy index valueModify the data of the array, VueUnable to detect changes in the arrayBecauseThere are no corresponding set and get methods。 As follows:

<template>
  <div>
    <li v-for="(item, index) of list" :key="index">{{ item }}</li>
    < button @ Click = "changelist" > Modify array value through index < / button >
  </div>
</template>

<script>
    export default {
     	data() {
          return {
            list: [0, 1, 2, 3]
          } 
        },
        methods: {
          change() {
            //If the array value is modified directly through the index, it cannot be updated to the view
            this.list[0] = 5
          }
        }   
    }
</script>

[Vue | hole mending | 22] vue2 monitoring data principle (array)

3. Solutions

1) Method 1: useVue.setAPI (in components, usethis.$set)Make modifications

this.$ Set (array to be modified, index value to be modified, changed value)

change() {
   this.$ Set (this.list, 0, changed value)
}

2) Method 2: Vue repackages the seven common operation methods of the array to ensure that the array changes can be monitored before the array operation. It includes the following seven types:

  • Push: insert from the end of the array
  • Pop: remove from the end of the array
  • Unshift: insert from array header
  • Shift: remove from array header
  • Splice: replace
  • Sort: sort
  • Reverse: reverse the order

Change the example code in point 2 into the following (either method 1 or method 2):

//Method 1
change() {
   this.$ Set (this.list, 0, 'changed value')
}

//Method 2
change() {
   //Can monitor the changes of hobby
   this. list. Splice (0, 1, 'changed value')
}

[Vue | hole mending | 22] vue2 monitoring data principle (array)

4. Summary

  • In vue2,Object.definePropertyUnable to monitor array changes
  • Therefore, vue2 is right7 common array operation methodsAll of these operations can be monitored through Vue array