<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vue原理</title>
</head>
<body>
<script src="./index.js"></script>
<script>
let vm = new myVue({
data: {
age: 12,
score: {
math: 99,
english: 89
}
}
})
</script>
</body>
</html>
class myVue {
constructor(options) {
this._options = options;
this.$data = options.data;
this._initData()
}
<!-- more -->
_initData() {
let data = this.$data
let keys = Object.keys(data)
for (let index = 0; index < keys.length; index++) {
Object.defineProperty(this, keys[index], {
enumerable: true,
configurable: true,
get: function proxyGetter() {
return data[keys[index]]
},
set: function proxySetter(val) {
data[keys[index]] = val
}
})
}
observe(data)
}
}
function observe(data) {
const type = Object.prototype.toString.call(data)
if (type !== "[object Array]" && type !== "[object Object]") {
return;
}
new Observer(data)
}
function defineReactive(obj, objKey, value) {
observe(obj[objKey])
Object.defineProperty(obj, objKey, {
enumerable: true,
configurable: true,
get: function proxyGetter() {
console.log(`${objKey}取值`);
return value
},
set: function proxySetter(val) {
console.log(`${objKey}发生了改变`);
value = val
}
})
}
class Observer {
constructor(data) {
this._walk(data)
}
_walk(data) {
let keys = Object.keys(data)
for (let index = 0; index < keys.length; index++) {
defineReactive(data, keys[index], data[keys[index]])
}
}
}
v1.4.18