方法 | 概念 | 兼容性 | 监听 | 应用 |
---|---|---|---|---|
defineproperty | 数据劫持 | 任意浏览器 | 监听对象各个属性,无法监听新增属性。使用时需要遍历对象每个属性,对性能有影响。无法监听数组操作 | vue2 |
proxy | 数据代理 es6出现 | 低版本ie、百度、QQ浏览器不支持,无法使用polyfill补平 | 监听对象本身,可以监听新增属性、数组操作,性能好 | vue3 |
proxy其他优势:
1.内置Reflect提供函数式操作,操作更规范
2.提供13种对象拦截方法
// defineProperty
function observe(obj, callback) {
const newObj = {}
Object.keys(obj).forEach(key => {
Object.defineProperty(newObj, key, {
configurable: true,
enumerable: true,
get() {
return obj[key]
},
// 当属性的值被修改时,会调用set,这时候就可以在set里面调用回调函数
set(newVal) {
obj[key] = newVal
callback(key, newVal)
}
})
})
return newObj
}
// proxy
function observe(obj, callback) {
return new Proxy(obj, {
get(target, key) {
return target[key]
},
set(target, key, value) {
target[key] = value
callback(key, value)
}
})
}
网友评论