vue2
let oldProtoMethods = Array.prototype;
let proto = Object.create(oldProtoMethods);
['push','pop','shift','unshift'].forEach(method => {
Object.defineProperty(proto,method,{
get(){
update();
oldProtoMethods[method].call(this,...arguments)
}
})
})
function observer(target){
if(typeof target !== 'object'){
return target
}
if(Array.isArray(target)){
Object.setPrototypeOf(target,proto);
for(let i = 0; i < target.length; i++){
observer(target[i])
}
return
};
for(let key in target){
defineReactive(target,key,target(key))
}
}
function update() {
console.log('更新')
}
function defineReactive(obj, key, value) {
observer(value);
Object.defineProperty(obj, key, {
get() {
return value
},
set(newVal) {
if (newVal !== value) {
observer(value);
update();
}
}
})
}
let obj = {hobby:[{name:'youxuan'},'喝']}
observer(obj)
obj.hobby[0].name = 'webyouxuan';
console.log(obj)
vue3
let proxyObj = new Proxy({}, {
get: (target, key, receiver) => {
console.log(`getting:${key}~`);
return target[key];
},
set: (target, key, value, receiver) => {
console.log(target, key, value, receiver);
return target[key] = value;
}
})
proxyObj.val = 1;
console.log(proxyObj.val);
let proxyArr = new Proxy([], {
get: (target, key, receiver) => {
console.log(`getting:${key}~`);
return target[key];
},
set: (target, key, value, receiver) => {
console.log(target, key, value, receiver);
return target[key] = value;
}
})
proxyArr[0] = 2;
console.log(proxyArr[0]);