Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities

The core of the responsive-type principle in VUe3 is to intercept any operation on any attribute of the target object through Proxy, such as adding, deleting, changing and checking, etc. There are 13 kinds. New Proxy() passes in two parameters, the first is the target object to be propositioned, and the second is the handler object, whose properties are the corresponding 13 functions that define the behavior of the new Proxy object when performing various operations. ShallowReactive: shallowReactive: shallowReactive: shallowReactive: shallowReactive: shallowReactive

function shallowReactive(target) {
  if (target && typeof target === 'object') {
    return new Proxy(target, handler)
  } else {
    return target
  }
}
Copy the code

If (target &&); if (target &&); if (target &&);

The handler object:

const handler = {
  get(target, prop) {
    console.log('read')
    return Reflect.get(target, prop)
  },
  set(target, prop, value) {
    console.log('change')
    return Reflect.set(target, prop, value)
  },
  deleteProperty(target, prop) {
    console.log('delete')
    return Reflect.deleteProperty(target, prop)
  }
}
Copy the code

We can test this by creating a new plain object, obj:

const obj = {
  name: 'Jay'.newAlbum: {
    time: 'soon'}}Copy the code

Pass obj to shallowReactive, assign the return value to proxyObj, and perform the += operation on it.

const proxyObj = shallowReactive(obj)
proxyObj.name += 'Chou' 
Copy the code

Now print the proxy object console.log(proxyObj) to get the following result:

Print the target object console.log(obj) :

You can see that the names of both the proxy object and the target object have been changed, and that “read” and “modify” are printed, proving that get and set fires in the handler object. Note: If Reflect’s attribute function is not called in set or get, Return reflect. get(target, prop) and return reflect. set(target, prop, value);

You can see that neither the proxy object nor the target object’s name attribute has been changed.

If you just comment return reflect.get (target, prop), the result looks like this:

Proxyobj. name is undefined because reflect. get is not returned.

So each attribute of the Handler object needs to return the corresponding Reflect attribute. Reflect is a built-in object that provides methods to intercept JS operations. Note that Reflect is not a function object and cannot be constructed, meaning that all of its methods are static. These methods correspond to the methods of Proxy handler, and there are also 13 methods. In summary, we use Proxy to hijack the internal data of the object, and use Reflect to manipulate the internal data of the object.

This is the end of the vuE3, I am also learning more knowledge, shortcomings also hope you don’t be so generous to correct ~