html代码
<!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>
<div id="app">{{name}}</div>
<script src="vue.js"></script>
<script>
var vm = new Vue({
data: {
name: {
age: 14,
sex: 'aa',
children: {
name: 'son',
age: 18
}
}
}
})
</script>
</body>
</html>
vue.js代码
function Vue(options) {
this.$data = options.data
new Observe(this.$data)
dataAgancy.call(this, this.$data)
}
function Observe(data) {
walk(data)
}
function walk(obj) {
for (const k in obj) {
let value = obj[k]
Object.defineProperty(obj, k, {
enumerable: true,
configurable: true,
get() {
return value
},
set(newValue) {
console.log('set')
walk(newValue)
value = newValue
}
})
if (value instanceof Object) {
walk(value)
}
}
}
function dataAgancy(data) {
for (const k in this.$data) {
console.log(k)
Object.defineProperty(this, k, {
enumerable: true,
configurable: true,
get() {
return this.$data[k]
},
set(newValue) {
this.$data[k] = newValue
}
})
}
}