Why use Proxy API instead of defineProperty API in Vue3.0?

 一、Object.defineProperty

Definition: Object.defineProperty() The method defines a new property directly on an object, or modifies an existing property of an object, and returns this object

Why can it be responsive? via defineProperty two properties, getandset

  • get

The property's getter function, which is called when the property is accessed. No parameters are passed in during execution, but the this object will be passed in (due to the inheritance relationship, this here is not necessarily the object defining the property). The return value of this function will be used as the value of the property

  • set

The setter function of the property, when the property value is modified, this function will be called. This method accepts a parameter (that is, the new value to be assigned), which will be passed in the this object at the time of assignment. The default is undefined

 define a reactive functiondefineReactive:

Call defineReactive, trigger method when data changes update, realize data responsive

 

When there are multiple objects key, traversal is required

 

If there are nested objects, you also need to defineReactiverecurse in

When keyassigning an object, you also need to setrecurse in the attribute

The above example can realize the basic response to an object, but there are still many problems

Now delete and add attributes to an object, which cannot be hijacked

When we listen to an array, it doesn't work so well

It can be seen that the data apicannot be hijacked, so that the data responsiveness cannot be realized.

So in Vue2, add set, delete API, and apirewrite the array method

Another problem is that if there is a deep nested object relationship, it needs to be monitored deeply, which causes a huge performance problem

Two , proxy

 ProxyThe monitoring is for an object, then all operations on this object will enter the monitoring operation, which can completely proxy all attributes

The code is shown below:

Define a reactive methodreactive

Test the operation of simple data and find that it can be hijacked and then test the nested object. At this time, it is not so OK

 

If you want to solve it, you need to getperform a layer of proxy on top of it

 3. Summary

Object.definePropertyCan only traverse object properties for hijacking

ProxyDirectly hijack the entire object and return a new object, we can only operate the new object to achieve responsive purposes

ProxyYou can directly monitor the changes of the array ( push, shift, splice)

ProxyThere are as many as 13 interception methods, not limited to apply, ownKeys, deleteProperty, hasetc., which are Object.definePropertynot available

Proxy Not compatible with IE, nor  polyfilldefineProperty can support IE9

references

https://developer.mozilla.org/zhCN/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty

Guess you like

Origin blog.csdn.net/m0_64479814/article/details/130210577