feat(reactivity): add isShallow api

This commit is contained in:
Evan You
2022-01-18 09:17:22 +08:00
parent 0c06c748a5
commit 9fda9411ec
9 changed files with 39 additions and 15 deletions

View File

@@ -84,6 +84,8 @@ function createGetter(isReadonly = false, shallow = false) {
return !isReadonly
} else if (key === ReactiveFlags.IS_READONLY) {
return isReadonly
} else if (key === ReactiveFlags.IS_SHALLOW) {
return shallow
} else if (
key === ReactiveFlags.RAW &&
receiver ===

View File

@@ -22,6 +22,7 @@ export {
readonly,
isReactive,
isReadonly,
isShallow,
isProxy,
shallowReactive,
shallowReadonly,

View File

@@ -17,6 +17,7 @@ export const enum ReactiveFlags {
SKIP = '__v_skip',
IS_REACTIVE = '__v_isReactive',
IS_READONLY = '__v_isReadonly',
IS_SHALLOW = '__v_isShallow',
RAW = '__v_raw'
}
@@ -24,6 +25,7 @@ export interface Target {
[ReactiveFlags.SKIP]?: boolean
[ReactiveFlags.IS_REACTIVE]?: boolean
[ReactiveFlags.IS_READONLY]?: boolean
[ReactiveFlags.IS_SHALLOW]?: boolean
[ReactiveFlags.RAW]?: any
}
@@ -87,7 +89,7 @@ export type UnwrapNestedRefs<T> = T extends Ref ? T : UnwrapRefSimple<T>
export function reactive<T extends object>(target: T): UnwrapNestedRefs<T>
export function reactive(target: object) {
// if trying to observe a readonly proxy, return the readonly version.
if (target && (target as Target)[ReactiveFlags.IS_READONLY]) {
if (isReadonly(target)) {
return target
}
return createReactiveObject(
@@ -226,6 +228,10 @@ export function isReadonly(value: unknown): boolean {
return !!(value && (value as Target)[ReactiveFlags.IS_READONLY])
}
export function isShallow(value: unknown): boolean {
return !!(value && (value as Target)[ReactiveFlags.IS_SHALLOW])
}
export function isProxy(value: unknown): boolean {
return isReactive(value) || isReadonly(value)
}

View File

@@ -16,10 +16,6 @@ export interface Ref<T = any> {
* autocomplete, so we use a private Symbol instead.
*/
[RefSymbol]: true
/**
* @internal
*/
_shallow?: boolean
}
type RefBase<T> = {
@@ -102,9 +98,9 @@ class RefImpl<T> {
public dep?: Dep = undefined
public readonly __v_isRef = true
constructor(value: T, public readonly _shallow: boolean) {
this._rawValue = _shallow ? value : toRaw(value)
this._value = _shallow ? value : toReactive(value)
constructor(value: T, public readonly __v_isShallow: boolean) {
this._rawValue = __v_isShallow ? value : toRaw(value)
this._value = __v_isShallow ? value : toReactive(value)
}
get value() {
@@ -113,10 +109,10 @@ class RefImpl<T> {
}
set value(newVal) {
newVal = this._shallow ? newVal : toRaw(newVal)
newVal = this.__v_isShallow ? newVal : toRaw(newVal)
if (hasChanged(newVal, this._rawValue)) {
this._rawValue = newVal
this._value = this._shallow ? newVal : toReactive(newVal)
this._value = this.__v_isShallow ? newVal : toReactive(newVal)
triggerRefValue(this, newVal)
}
}