1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| <!DOCTYPE html> <html lang="en">
<head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head>
<body> <script src="./js/Dep.js"></script> <script src="./js/Observer.js"></script> <script src="./js/Watcher.js"></script>
<script> class Vue { constructor(options = {}) { this.$options = options let data = this._data = this.$options.data Object.keys(data).forEach(key=>{ this.myProxy(key) }) observe(data, this) } $watch(expOrFn, cb, options) { new Watcher(this, expOrFn, cb) } myProxy(key){ var obj = this Object.defineProperty(obj,key,{ enumerable:true, configurable:true, get(){ return obj._data[key] }, set(newV){ obj._data[key] = newV } }) } }
const vm = new Vue({ data:{ a:1, b:2 } })
vm.$watch('a',()=>{ console.log("正在观测a") })
setTimeout(()=>{ vm.a = 233 },2000) </script> </body>
</html>
|