<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>星月不负赶路人</title>
</head>
<body>
<script src="./index.js"></script>
<script type="text/javascript">
const proxyUser1 = shallowReactive({
name: "明月",
car: {
color: "white",
},
});
const proxyUser2 = reactive({
name: "明月",
car: {
color: "white",
},
});
delete proxyUser2.car.color;
</script>
</body>
</html>
- 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
const reactiveHandler = {
get(target, prop) {
const result = Reflect.get(target, prop);
console.log("拦截了读取数据", prop, result);
return result;
},
set(target, prop, value) {
const result = Reflect.set(target, prop, value);
console.log("拦截了修改数据或者是添加属性", prop, value);
return result;
},
deleteProperty(target, prop) {
const result = Reflect.deleteProperty(target, prop);
console.log("拦截了删除数据", prop);
return result;
},
};
function shallowReactive(target) {
if (target && typeof target === "object") {
return new Proxy(target, reactiveHandler);
}
return target;
}
function reactive(target) {
if (target && typeof target === "object") {
if (Array.isArray(target)) {
target.forEach((item, index) => {
target[index] = reactive(item);
});
} else {
Object.keys(target).forEach((key) => {
target[key] = reactive(target[key]);
});
}
return new Proxy(target, reactiveHandler);
}
return target;
}
- 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
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59