1 <body> 2 <script src="./Dvue.js"></script> 3 <script> 4 const app = new DVue({ 5 data: { 6 test: "I am test", 7 foo: { 8 bar: "bar" 9 } 10 } 11 }) 12 13 app.$data.test = "hello kaikeba!" // update the property: the Hello kaikeba! 14 // App = $ data.foo.bar." The Hello "! 15 </ Script > 16 </ body >
Dvue.js
. 1 class DVue { 2 constructor (Options) { . 3 the this . = $ Options Options . 4 . 5 // data of response . 6 the this . $ Data = options.data . 7 the this .observe ( the this . $ Data) . 8 } . 9 10 the observe (value ) { 11 // determines whether the target value 12 is iF (! value || typeof value! == 'Object' ) { 13 is return 14 } 15 16 // traverse the object 17 Object.keys (value) .forEach (Key => { 18 is the this .defineReactive (value, Key, value [Key]) . 19 }) 20 is } 21 is 22 is // response data of 23 is defineReactive (obj, Key, Val) { 24 // determines whether the call can continue (if there are objects) within Val 25 the this .observe (Val) // recursive solution nested data 26 is 27 Object.defineProperty (obj, Key, { 28 GET () { 29 // read when taken Dep.target determines whether there is, if the method is called addDep deps Dep.target added to the array 30 return Val 31 is }, 32 SET (newVal) { 33 is // whether the same before and after the data update determination 34 is IF (newVal === Val) { 35 return ; 36 } 37 [ Val = newVal 38 is the console.log ( `$} {Key attributes updated: $ {val } `) 39 } 40 }) 41 } 42 }