console
const $app1 = document.querySelector('#app1')
const $app2 = document.querySelector('#app2')
let activeEffect;
const effect = function (fn) {
console.log(fn)
activeEffect = fn
fn()
}
const bucket = new Set()
const state = new Proxy({ text1: 'hello text1', text2: 'hello text2' }, {
get(target, key) {
const value = target[key]
bucket.add(activeEffect)
console.log(`get${key}:${value}`)
return value
},
set(target, key, newValue) {
console.log(`set${key}:${newValue}`)
target[key] = newValue
bucket.forEach((fn) => fn())
}
})
effect(function effect1() {
console.log('执行了effect1')
$app1.innerText = state.text1
})
effect(function effect2() {
console.log('执行了effect2')
$app2.innerText = state.text2
})
setTimeout(() => {
state.text1 = 'hello xuqiushi---1'
state.text2 = 'hello xuqiushi---2'
}, 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="app1"></div>
<div id="app2"></div>
</body>
</html>
#app1{
width: 200px;
height: 100px;
background-color: #ffffff;
}
#app2{
width: 200px;
height: 100px;
background-color: lightcyan;
}