变量为原始类型时Set存储
变量为对象时可以用map存储
多个对象时用weakMap存储 https://www.gxlsystem.com/qianduan-20707.html
<!DOCTYPE html>
<html>
<head>
<title>document.write() Example</title>
</head>
<body>
<script type="text/javascript">
const data = {ok:true, text:'hello world'}
const obj = new Proxy(data, {
get(target, key) {
track(target, key);
console.log(target[key])
return target[key]
},
set(target, key, newVal) {
target[key] = newVal;
trigger(target, key);
}
})
function track(target, key) {
if (!activeEffect) return
let depsMap = bucket.get(target)
console.log(depsMap)
if (!depsMap) {
bucket.set(target, (depsMap = new Map()))
}
let deps = depsMap.get(key)
if (!deps) {
depsMap.set(key, (deps = new Set()))
}
deps.add(activeEffect)
}
function trigger(target, key) {
const depsMap = bucket.get(target)
if (!depsMap) return
const effects = depsMap.get(key)
console.log(effects)
effects && effects.forEach(fn => fn())
}
</script>
</body>
</html>
|