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
60
61
62
63
64
65
66
67
68
|
// baseHandler.ts 修改
const getShallowReactive = createGetter(false, true)
const getShallowReadonly = createGetter(true, true)
function createGetter(isReadonly: boolean = false, isShallow: boolean = false) {
return function get(target, key) {
const value = Reflect.get(target,key)
if (isShallow) {
return value
}
if (key === ReactiveFlags.IS_READONLY) {
return isReadonly
} else if (key === ReactiveFlags.IS_REACTIVE) {
return !isReadonly
}
if (isObject(value)) {
return isReadonly ? readonly(value) : reactive(value)
}
if (!isReadonly) {
trigger(target, key)
}
return value
}
}
const mutableHandlerShallowReactive = {
get: getShallowReactive,
set,
}
const mutableHandlerShallowReadonly = {
get: getShallowReadonly,
set(target, key, value) {
console.warn(`key :"${String(key)}" set 失败,因为 target 是 readonly 类型`, target);
return true
}
}
export {
mutableHandlerShallowReactive,
mutableHandlerShallowReadonly,
}
// reactive.ts
import { mutableHandlerShallowReactive, mutableHandlerShallowReadonly} from ./baseHandler.ts
function shallowReactive(raw: Object) {
return createActiveObject(raw, mutableHandlerShallowReactive)
}
function shallowReadonly(raw: Object) {
return createActiveObject(raw, mutableHandlerShallowReadonly)
}
function createActiveObject(target, baseHandler) {
return new Proxy(target, baseHandler)
}
export {
shallowReactive,
shallowReadonly,
}
|