console
const $app = document.querySelector('#app')
const bucket = new WeakMap()
let activeEffect;
const effect = function (fn) {
console.log(fn)
activeEffect = fn
fn()
}
const state = new Proxy({ name: 'hello text1', age: 22 }, {
get(target, key) {
const value = target[key]
if (!activeEffect) {
return
}
let depsMap = bucket.get(target)
if (!depsMap) {
bucket.set(target, (depsMap = new Map()))
}
let deps = depsMap.get(key)
if (!deps) {
depsMap.set(key, deps = new Set())
}
deps.add(activeEffect)
console.log(`获取${key}:${value}`)
return value
},
set(target, key, newValue) {
console.log(`设置${key}:${newValue}`)
target[key] = newValue
const depsMap = bucket.get(target)
if (!depsMap) {
return
} else {
const deps = depsMap.get(key)
if (!deps) {
return
}
deps.forEach(fn => fn())
}
}
})
effect(() => {
console.log('执行了effect')
$app.innerText = `hello ${state.name}, are you ${state.age} years old?`
})
setTimeout(() => {
state.name = 'Vue3'
state.age = 18
}, 2000)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div id="app"></div>
</body>
</html>
#app{
width: 200px;
height: 100px;
background-color: #ffffff;
}