Since Reactive is implemented using a Proxy, and you can also use a Proxy, how about we define a Proxy to use Reactive?

Let’s not worry about whether it makes sense or not, and then we have this code.

  /** * Use Proxy to define a reactive doll. *@param {*} _target Target to be intercepted *@param {*} The callback function */ after the callback attribute changes
  const myReactive = (_target, callback) = > {
    const proxy = new Proxy(_target, {
      get: function (target, key, receiver) {
        if (typeofkey ! = ='symbol') { // Don't ask me why I want to add this, because it will cause an error.
          console.log(`getting ${key}! `, target[key])
        } else {
          console.log('getting symbol:', key, target[key])
        }
        // Call the prototype method
        return Reflect.get(target, key, receiver)
      },
      set: function (target, key, value, receiver) {
        console.log(`setting ${key}:${value}! `)
        // Call the prototype method
        return Reflect.set(target, key, value, target) // The template is not automatically updated when writing receiver}})// Return the instance
    return proxy
  }
Copy the code

According to the online introduction, I wrote the Proxy function, and then happily installed reactive, and then bound the template to set the update button.

After the result is updated, P does not reflect.

Reactive. There’s no reason not to refresh the template.

Stuck for days and then realized you were too stupid to set breakpoints to track it? The whole section of the source code do not understand, see a set tracking also do not understand?

After following several times, I finally understood that the set made a comparison judgment between target and receiver, and the result was skipped.

So I changed receiver to target to see if he still jumped.

The template is finally refreshed.

Well, there’s no real use in putting on a doll, just a little bit more insight into how Vue is responsive and how templates are refreshed.

Also, this does not support interception of child child attributes. You can only intercept one layer of attributes, but if you want to intercept further, you need to do a recursion and set a Proxy for each nested object. Wait, reactive doesn’t seem to work that way…

This is the listening result of the template call:

getting __v_isRef! undefined
getting toJSON! undefined
getting symbol: Symbol(Symbol.toStringTag) undefined
getting symbol: Symbol(Symbol.toStringTag) undefined
getting symbol: Symbol(Symbol.toStringTag) undefined
getting name! jyk
getting age! 18
Copy the code