function observe(data) {
if (!data || typeof data !== 'object') return
for (const key in data) {
let val = data[key]
Object.defineProperty(data, key, {
enumerable: true,
configurable: true,
get: function () {
track(data, key)
return val
},
set: function (newVal) {
trigger(data, key, newVal)
val = newVal
},
})
if (typeof val === 'object') {
observe(val)
}
}
}
function track(data, key) {
console.log('get data', key)
}
function trigger(data, key, value) {
console.log('set data', key, ':', value)
}
var data = {
name: 'ma',
friends: [1, 2, 3],
}
observe(data)
console.log(data.name)
data.name = 'other'
data.friends[0] = '1'
//data.friends 会打印 get data friends
data.friends[3] = '4' //非响应式
//data.friends 会打印 get data friends
data.age = 20 //非响应式
缺点 :对对象观测后,之后新增的属性无响应式
Proxy对象用于创建一个对象的代理,从而实现基本 操作的拦截和自定义(如属性查找、赋值、枚举、函 数调用等)。
Reflect 是一个内置的对象,它提供拦截JavaScript 操作的方法,这些方法和 Proxy handlers 相同。
Reflect.set (target, propertyKev, value [, receiver])
将值分配给属性的函数。返回一个 Boolean,如果更 新成功,则返回true。
Reflect.get(tarqet, propertyKev [ ,receiver] )
获取对象身上某个属性的值,类似于 target[name]
const dinner = {
meal: 'tacos'
}
const handler = {
get (target, prop) {
console.log('get___', prop)
return Reflect.get(...arguments)
},
set(target, key, value) {
console.log('set___', key, value)
return Reflect.set(...arguments)
}
}
const proxy = new Proxy(dinner, handler)
console.log(proxy.meal)
proxy.food='abc'
function reactive(obj) {
const handler = {
get(target, prop, receiver) {
track(target, prop)
const value = Reflect.get(...arguments)
if (typeof value === 'object') {
return reactive(value)
} else {
return value
}
},
set(target, key, value, receiver) {
trigger(target, key, value)
return Reflect.set(...arguments)
}
}
return new Proxy(obj, handler)
}
function track(data, key) {
console.log('get data', key)
}
function trigger(data, key, value) {
console.log('set data', key, value)
}
const dinner = {
meal: 'tacos'
}
const proxy = reactive(dinner)
proxy.meal = 'apple'
proxy.list =[]
proxy.list.push(1) // 响应式