手写Vue数据响应式原理
function isObserve(obj){
return obj !== null && !Array.isArray(obj) && typeof obj === 'object'
}
function observe(obj){
if(!isObserve(obj)){
return;
}
Object.keys(obj).forEach((key)=>{
var dep = new Dep()
var internalValue = obj[key];
observe(internalValue);
Object.defineProperty(obj,key,{
get(){
dep.depend();
return internalValue;
},
set(val){
observe(val)
internalValue = val;
dep.notify()
}
})
})
}
function Dep(){
this.subscribes = new Set();
}
Dep.prototype.depend = function(){
if(activeUpdate){
this.subscribes.add(activeUpdate)
}
}
Dep.prototype.notify = function(){
this.subscribes.forEach(fn => fn())
}
var activeUpdate = null;
function autorun(fn){
function Wrapper(){
activeUpdate = Wrapper;
fn();
activeUpdate = null;
}
Wrapper()
}
var state = {
name: 'diudiu',
age: 18,
addr: {
province: "四川",
city: '成都'
},
};
observe(state)
autorun(()=>{
if(state.age%2!==0){
console.log("姓名", state.name, "地址", state.addr.province, state.addr.city);
}
})
state.age = 19;
state.name = '勾勾'
state.addr.province = "上海";
state.addr.city = "南京";