代码:
<!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> <script> let state = { count: 0 }; // 变成响应式的数据 let active; function defineReactive(obj) { for (let key in obj) { let value = obj[key]; // 对象对应的值 let dep = []; Object.defineProperty(obj, key, { get() { if (active) { dep.push(active); // 依赖收集 return value; } }, set(newValue) { // 触发更新 value = newValue; dep.forEach((watcher) => watcher()); }, }); } } defineReactive(state); const wacther = (fn) => { active = fn; fn(); // 调用函数 active = null; }; wacther(() => { app.innerHTML = state.count; // 取值 }); wacther(() => { console.log(state.count); }); </script> </body> </html>
.