This is the 28th day of my participation in the August Challenge

preface

Vue 2.x uses the object.defineProperty () method to detect Object attribute changes, but this method has some inherent drawbacks:

  1. Poor performance
  2. New attributes on objects cannot be detected
  3. Undetected while changing array length

Implementation principle of Vue 3.0 responsive system

Vue 3.0 uses ES6 proxies instead of object.defineProperty () for better performance, and arrays, like objects, can directly trigger get() and set() methods. A Proxy, called a Proxy, is a wrapper that intercepts and changes the operations of the underlying JavaScript engine.

Calling New Proxy(target, handler) creates a Proxy for a target object that intercepts low-level object operations on the target within the JavaScript engine, triggering trap functions that respond to specific operations. When you call the Proxy constructor, you pass in two parameters, target as the target object; Handler is a handler object that contains trap functions.

// Processor object
const baseHandler = {
  // Trap function, triggered when reading the property value
  // Target is the target object
  // The property argument is the name of the property to get
  The receiver parameter is a Proxy object or an object that inherits from a Proxy
  get(target, property, receiver){
    console.log('Get value')},// Trap function, triggered when writing property values
  // The value argument is the new attribute value
  set(target, property, value, receiver){
    console.log('Set value')},// Trap function that is triggered when an attribute value is deleted
  deleteProperty(target, property){
    console.log('Delete attribute')}}// Target object
const target = {name: 'jack'}
// Create a proxy object for the target object
const proxy = new Proxy(target, baseHandler)
// Read the property value
proxy.name
// Set the property value
proxy.name = 'tom'
// Delete attributes
delete proxy.name
Copy the code

Operations on the proxy object then trigger the corresponding trap function in the processor object, where custom business logic can be added for property access to the target object.

The above code runs as follows:

Get value Set value delete propertyCopy the code