console
const bucket = new WeakMap()
let activeEffect
const effect = function (fn) {
activeEffect = fn
fn()
}
function trackFunc(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)
}
function trigger(target, key) {
const depsMap = bucket.get(target)
if (!depsMap) {
return
}
const deps = depsMap.get(key)
deps && deps.forEach(fn => fn())
}
function reactive(data){
return new Proxy(data,{
get:(target,key)=>{
const value=target[key]
trackFunc(target,key)
return value
},
set:(target,key,newValue)=>{
target[key]=newValue
trigger(target,key)
}
})
}
const $app=document.querySelector('#app')
const nameObj=reactive({
name:'akimixu'
})
const ageObj=reactive({
age:100
})
effect(()=>{
console.log("执行effect函数")
$app.innerText=`hello ${nameObj.name},are you ${ageObj.age} years old?`
})
setTimeout(()=>{
nameObj.name="徐秋实"
},1000)
setTimeout(()=>{
ageObj.age=123
},5000)
<!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;
}