Vue响应式

首先看端代码如何将一个普通对象转为可以监控到变化的对象

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
function touch(parent, key, obj) {
if (typeof obj === 'object') {
for (let i in obj) {
let result = touch(obj, i, obj[i]);
if (typeof obj[i] !== 'object') {} else {
let curVal = obj[i];
Object.defineProperty(obj, i, {
get: function() {
console.log('get', i);
return curVal;
},
set: function(value) {
console.log('set', i, value);
curVal = value;
}
});
}
}
} else {
let currentValue = obj;
Object.defineProperty(parent, key, {
get: function() {
console.log('get', key);
return currentValue;
},
set: function(value) {
console.log('set', key, value);
currentValue = value;
}
});
return parent;
}
}
var objtest = {
a: 1,
b: {
c: 2,
d: 3,
e:{
f:4,
g:5
}
}
};
touch(window, 'getObj', objtest);
objtest.b.c='new';