Compare the responses of VUE2 and VUE3

Response of VUE2

  • Core:
  1. Object: ThroughdefinePropertyHijacking (monitoring and intercepting) the reading and modification of existing private properties of an object
  2. Array: Hijack element changes by overriding an array to update a series of methods that update the array’s elements
   Object.defineProperty(date,'count',{
            get(){},
            set()
        })
Copy the code

Question:

  • Object direct sky sword properties or delete existing properties interface will not automatically update
  • Update directly by replacing elements with subscriptslength, the interface will not be automatically updated

Vue3’s response

  • Intercepts any operation (13 kinds) on any property of data through Proxy, including familiar read and write, delete, etc…

  • Reflect is used to dynamically perform specific operations on the corresponding properties of the proxy object

  • Documents: developer.mozilla.org/zh-CN/docs/… Developer.mozilla.org/zh-CN/docs/…

    The following is an example of several common Proxy operations

Get (target,prop){return reflect.get (target,prop)}, Set (target,prop,value){return reflect.set (target,prop,value)}, {return reflect.deleteProperty (trget,prop)}}) proxy. name='Loin'Copy the code

Get attribute value

Let’s look at what the log is

Why is console.log(proxyuser.name) undefined? Since the name object is not reflected by the reflection object, we need to write return reflect.get (target,prop) in the get method

This is a small effect achieved with proxy and reflection objects that is relatively simple to understand

Change the add attribute value

Let’s look at the code below

The printed user looks like this

The set method of Proxy has three properties: target,prop, and val. The set method of Reflect also has three properties. Update the name of the Proxy by proxyUser. If you want to manipulate the attribute of girlFriend in user, such as user.girlfriend. Name, you can simply change the assignment.

Attribute values are added with the. Gender attribute. The set method ### is called once each time, either to change or to add, to delete the attribute value of the target object