About VUE two data hijacking methods

The essential difference between Object.defineProperty and Proxy

Let’s briefly talk about the following two methods of hijacking data
using arrays to illustrate: a=[1,2,3,4,5,6,7]. The length is 7
1, the position of the array is not fixed, and the data is changeable. For example, if the header data is deleted, the
subscript of the entire data is changed, which means the key and value are misaligned
. 2. For the array a, if I delete the first item of the data, it will trigger the set method 6 times, and actually modify one If the item hijacks all items, it causes a lot of waste of resources, which is not conducive to event performance
. 3. Interception can be implemented in Vue. Vue rewrites 7 methods of Array.

Not to mention the example

const arr = [1, 2, 3, 4, 5, 6,7]
for (let key in arr) {
    let value = arr[key]
    Object.defineProperty(arr, key, {
        get() {
            return value
        set(newValue) {
            return value = newValue

arr[ 0 ] = 7  // print: set: 0 to 999 
arr[ 4 ] // print: get: 3 
arr.shift() // will cause 6 forward shifts, so 6 get and 6 set

set: 0 to 7
get: 4
get: 0
get: 1
set: 0 to 2
get: 2
set: 1 to 3
get: 3
set: 2 to 4
get: 4
set: 3 to 5
get: 5
set: 4 to 6
get: 6
set: 5 to 7

Let’s talk about object.defineProperty hijacking the object

Object.defineProperty can only hijack the properties of the object, so it needs to be deeply traversed. If a property is an object, it needs to be deeply traversed again.

Proxy can hijack the entire object to return a new object, but the hijacking of Proxy is not complete. If the attribute is an object, it still needs to be traversed in depth, otherwise there is no way to synchronize it in real time.

Summary: The hijacking of Object.defineProperty must be hijacked in advance before the property can be monitored, otherwise the proxy will not be able to monitor and the proxy will proxy the entire object. After modification, the key will be notified through get/set that it needs to be acquired or modified. Even pre-increment property assignments can listen for values.

If the big guy finds something wrong, please leave a message, please forgive me for Xiaobai’s first words.

Leave a Comment

Your email address will not be published. Required fields are marked *