实现代码:
class Vue { constructor(options) { //缓存参数 this.$options = options; //需要监听的数据 this.$data = options.data; //数据监听 this.observe(this.$data); } observe(value) { if (!value || typeof value !== 'object') { return; } /* 取到每个key和value 调用definReactive 进行数据劫持 */ Object.keys(value).forEach(key => { //深度监听 if (typeof value[key] === 'object') { this.observe(value[key]); } this.definReactive(value, key, value[key]); }) } definReactive(obj, key, val) { Object.defineProperty(obj, key, { get() { return val; }, set(newVal) { if (newVal === val) { return; } val = newVal; console.log(`${key}属性更新了:${val}`); } }) } }
测试代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <script src="./vue.js"></script> <script> const app = new Vue({ data: { test: "i am test", foo: { bar: "bar" } } }); app.$data.test = "hello world!!"; app.$data.foo.bar = "oh my bar"; </script> </body> </html>
测试结果: