Data hijacking is the heart and foundation of Vue’s data-responsive approach, which adds additional operations to attribute changes by adding proxies

1, Vue 2.x data hijacking method

  Obejct.defineProperty(obj,prop,descriptor)
Copy the code

This method can modify the properties of an object precisely. Decriptor takes four parameters, namely

  • The data can be deleted and configured freely.
  • Enumerable: Whether a property is enumerable,
  • Get: a method that provides a getter for a property, undefined if there is no getter,
  • Set: a method that provides a setter for a property, otherwise undefined

Object.defineproperty () listens for data through getter/setter properties. Getters listen to access data, setters listen to modify data,

var value; Object.defineproperty (o, 'a', {get() {console.log(' get value ') return value}, Set (v) {console.log(' console.log ') value = QQQ}}) o.a = 'SSS' // console.log(o.a) // obtain the valueCopy the code
1.2 defects
  • Only getter/setter attributes cannot listen for property changes and deletions. When Vue 2.x assigns an object, it needs to be initialized, otherwise it needs to be Set with $Set().
  • You cannot listen for changes in the number of groups or the length of an array
  • Unable to intercept multi-layer nesting of object attributes,vue 2.x shows that watch fails to listen on multi-layer objects

2. Vue 3.x data hijacking method

In order to solve the above defects, ES6 introduces the concept of proxy. By creating a new instance object, it can operate the original object and provide 13 kinds of listening operations.

Reflect.apply(target,thisArg,args)
Reflect.construct(target,args)
Reflect.get(target,name,receiver)
Reflect.set(target,name,value,receiver)
Reflect.defineProperty(target,name,desc)
Reflect.deleteProperty(target,name)
Reflect.has(target,name)
Reflect.ownKeys(target)
Reflect.isExtensible(target)
Reflect.preventExtensions(target)
Reflect.getOwnPropertyDescriptor(target, name)
Reflect.getPrototypeOf(target)
Reflect.setPrototypeOf(target, prototype)

Copy the code
Let obj = new Proxy(arr, {get: function (target, key, receiver) {// console.log(" get array element "+ key); return Reflect.get(target, key, receiver); }, set: function (target, key, receiver) {console.log(' set array '); return Reflect.set(target, key, receiver); Obj [2] = 3 // result: set array // 2. Push,unshift add data obj. Push (4) // result: Set array * 2 (both index and length properties trigger setters) // // 3. Obj [5] = 5 // result: set array * 2 // // 4. Drop array element obj.splice(1, 1)Copy the code

Obviously, Proxy perfectly solves the problem of array monitoring and detection. For different methods of array adding data and deleting data, Proxy can intercept and deal with them well. In addition, Proxy also solves the problem of deep-seated nested objects very well. Specific readers can give examples for analysis.