(obj: any)
| 54 | |
| 55 | export function shallowReadonly<T extends object>(obj: T): Readonly<T> |
| 56 | export function shallowReadonly(obj: any): any { |
| 57 | if (!isObject(obj)) { |
| 58 | if (__DEV__) { |
| 59 | warn(`value cannot be made reactive: ${String(obj)}`) |
| 60 | } |
| 61 | return obj |
| 62 | } |
| 63 | |
| 64 | if ( |
| 65 | !(isPlainObject(obj) || isArray(obj)) || |
| 66 | (!Object.isExtensible(obj) && !isRef(obj)) |
| 67 | ) { |
| 68 | return obj |
| 69 | } |
| 70 | |
| 71 | const readonlyObj = isRef(obj) |
| 72 | ? new RefImpl({} as any) |
| 73 | : isReactive(obj) |
| 74 | ? observe({}) |
| 75 | : {} |
| 76 | const source = reactive({}) |
| 77 | const ob = (source as any).__ob__ |
| 78 | |
| 79 | for (const key of Object.keys(obj)) { |
| 80 | let val = obj[key] |
| 81 | let getter: (() => any) | undefined |
| 82 | const property = Object.getOwnPropertyDescriptor(obj, key) |
| 83 | if (property) { |
| 84 | if (property.configurable === false && !isRef(obj)) { |
| 85 | continue |
| 86 | } |
| 87 | getter = property.get |
| 88 | } |
| 89 | |
| 90 | proxy(readonlyObj, key, { |
| 91 | get: function getterHandler() { |
| 92 | const value = getter ? getter.call(obj) : val |
| 93 | ob.dep.depend() |
| 94 | return value |
| 95 | }, |
| 96 | set(v: any) { |
| 97 | if (__DEV__) { |
| 98 | warn(`Set operation on key "${key}" failed: target is readonly.`) |
| 99 | } |
| 100 | }, |
| 101 | }) |
| 102 | } |
| 103 | |
| 104 | readonlySet.set(readonlyObj, true) |
| 105 | |
| 106 | return readonlyObj |
| 107 | } |
searching dependent graphs…