proxy 兼容性不好,且无法polyfill ,vue2.x还会存在一段时间
监听对象,监听数组,复杂对象,深度监听
基础API object.defineProperty
function defineReactive(target,key,value){
//深度监听
observer(value)
//核心API
Object.defineproperty(target.key,{
get(){
return value
},
set(newValue){
if(newValue !== value){
//深度监听
observer(value)
}
}
})
}
defineProperty的几个缺点
- 深度监听,需要递归到底,一次性计算量大(可能会被卡死)
- 无法监听新增属性/删除属性(Vue.set Vue.delete)
- 无法原生监听数组,需要特殊处理
vue怎么监听数组
重新定义数组原型
const oldArrayProperty=Array.prototype
//创建新对象,原型指向oldArrayProperty,在扩展的方法不会影响原型
const arrProto=Object.create(oldArrayProperty)
['push','pop','shft','unshift','splice'].forEach(methodName=>{
arrProto[methodName]=function(){
updateView()// 触发视图更新
oldArrayProperty[methodName].call(this,...arguments);
//相当于: Array.prototype.push.call(this,...arguments);
}
})
//监听对象属性
function observer(target){
if(typeof target !=='object' || target === null){
//不是对象或数组
return target
}
if(Array.isArray(target)){
target.__proto__=arrProto
}
//重新定义各个属性(for in 也可以遍历数组)
for(let key in target){
defineReactive(target,key,target[key])
}
}