SOURCE

console 命令行工具 X clear

                    
>
console
//  const $app = document.querySelector('#app')
//   let state = {
//     text: 'hello fatfish'
//   }
//   function effect() {
//     $app.innerText = state.text
//   }
//   effect()
//   setTimeout(() => {
//     // 1秒后希望app的内容变成hello Vue3
//     state.text = 'hello Vue3'
//   }, 1000)
// 第一步:收集依赖(effect函数),在读取key时,将effect函数存储起来
// 第二步:设置值时,将依赖(effect函数)执行
const $app = document.querySelector('#app')


const bucket = new Set()

const state = new Proxy({ text: 'hello akimixu' }, {
    get(target, key) {
        const value = target[key]
        // 第一步:收集依赖,在读取key时,将effect函数存储起来
        bucket.add(effect)
        console.log(`get $ {key}: $ {value}`)
        return value
    },
    set(target, key, newValue) {
        console.log(`set $ {key}: $ {newValue}`)

        target[key] = newValue
        // 第二步:设置值时,将依赖执行
        bucket.forEach((fn) => fn())
    }
})

function effect() {
    console.log("执行了对应的fn")
    $app.innerText = state.text
}

effect()

setTimeout(() => {
    state.text = 'hello xuqiushi'
}, 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;
}