首先来了解下副作用函数和响应式数据
1.副作用函数
副作用函数指的是能够产生副作用的函数,并且会对函数外的值造成一定影响
let val = 1
function effect(){
val = 2
}
function effect(){
document.body.innerText = "hello"
}
2.响应式数据
通过拦截对象的setter和getter来实现响应式数据。(proxy和Object.defineProperty)
3.响应式数据
const data = {text:"hello world"};
const bucket = new Set();
const obj = new Proxy(data,{
get(target,key){
bucket.add(effect);
return target[key];
},
set(target,key,newVal){
target[key] = newVal;
bucket.forEach(fn => fn());
return true;
}
})
function effect(){
document.body.innerText = obj.text;
}
effect();
setTimeout(() => {
obj.text = "hello vue";
},1000)
4.总结
-
每次都通过effect名字来获取副作用函数,是一种硬编码方式。
-
简单实现了一个响应式的系统。