Vue3 data responsive principle

core:


const userData = {
    
    
	name: "John",
    age: 12
};

let proxyUser = new Proxy(userData, {
    
    
	// 拦截读取属性值
    get (target, prop) {
    
    
    	return Reflect.get(target, prop)
    },
    // 拦截设置属性值或添加新属性
    set (target, prop, value) {
    
    
    	return Reflect.set(target, prop, value)
    },
    // 拦截删除属性
    deleteProperty (target, prop) {
    
    
    	return Reflect.deleteProperty(target, prop)
    }
})
// 设置属性值
proxyUser.name = 'bob'
proxyUser.age = 13

// 添加属性
proxyUser.sex = '男'
console.log(user)

// 删除属性
delete proxyUser.sex
console.log(user)

How is Vue3's responsiveness better than Vue2?

  1. It is more efficient. In Vue2, it is assumed to monitor an object. There are 10,000 properties in the object. He needs to loop through each property and add set and get methods to each property through Object.defineProperty of each property. , then if there are 10,000, 10,000 pairs of get and set methods must be added, so the efficiency is very low; in Vue3, directly add a proxy object to reflect, and then call related methods to solve this problem;
  2. Responsive in Vue3 is a deep level of monitoring, which can monitor objects and arrays in objects;

Guess you like

Origin blog.csdn.net/weixin_44684357/article/details/132418169