响应数据原理: 初始化通过Proxy get方法收集依赖(dep对象的作用)---> 数据改变触发set--> set触发notify(更新依赖)
--> 再更改对应的dom(通过diff算法,patchVnode对比dom,对比根节点再创建等功能)--->重新render(渲染)
// vue2 是通过defineproperty 数据响应绑定
var obj = {
na: 'liu man',
age: 666
}
// Object.defineProperty 方法会直接在一个对象上定义一个新属性,或者修改一个对象的现有属性,并返回此对象。
// 缺点不能深度监听,需递归
var _value = obj.na
Object.defineProperty(obj,'na',{
// value: 'liu man',
// writable: true, // 是否可写 默认可写
// enumerable: true, // 是否可枚举 默认可枚举
// configurable: true // 是否可删除 默认可删除
configurable: false,
get: function() {
console.log('get');
return _value
},
set: function(newValue) {
console.log('set');
return _value = newValue
}
})
console.log(obj.na = '100');
console.log(obj.na);
console.log('---------');
// 如果在对象中存在,则返回给定的属性的属性描述符
console.log(Object.getOwnPropertyDescriptor(obj,'na'));
// vue3 是通过Proxy 数据响应绑定
var data = {
na: 'liu man',
age: 666
}
// 优势1)在于代理整个对象 而不是单个属性, 2)不会改变原对象,直接返回一个新的对象 3)不需要递归
const dataProxy = new Proxy(data,{
// target原对象,key原对象键值,
get:function(target,key,receiver){
// 这里也可以处理一些逻辑,比如登录了才能取到数据
return target[key]
},
set:function(target,key, newValue, receiver){
//类似 target[key] = value
return Reflect.set(target,key,newValue)
}
})
console.log('-----------');
console.log(dataProxy.na = 'coo');
console.log(dataProxy.na);
Object.defineProperty 劫持和代理
let data = {
name: 'cookie',
age: 26
}
let _this = {}
for (const key in data) {
Object.defineProperty(_this,key,{
get() { //用来获取扩展属性值的,当获取该属性值会调用get方法
console.log('get()');
return data[key]
},
set(newVal) { // 能获取到新的值
console.log('set',newVal);
// _this.name = '11' // 这样会陷入死循环
data[key] = newVal
}
})
}
console.log(_this);
// 通过Object.defineProperty的get方法添加的扩展属性不能直接对对象的属性修改
_this.name = '11'
console.log(_this.name); // 读取值会调用get方法