import { ref, isRef } from '../src/ref'
-import { reactive, isReactive, toRaw, markNonReactive } from '../src/reactive'
+import {
+ reactive,
+ isReactive,
+ toRaw,
+ markNonReactive,
+ shallowReactive
+} from '../src/reactive'
import { mockWarn } from '@vue/shared'
import { computed } from '../src/computed'
expect(isReactive(obj.foo)).toBe(true)
expect(isReactive(obj.bar)).toBe(false)
})
+
+ describe('shallowReactive', () => {
+ test('should not make non-reactive properties reactive', () => {
+ const props = shallowReactive({ n: { foo: 1 } })
+ expect(isReactive(props.n)).toBe(false)
+ })
+
+ test('should keep reactive properties reactive', () => {
+ const props: any = shallowReactive({ n: reactive({ foo: 1 }) })
+ props.n = reactive({ foo: 2 })
+ expect(isReactive(props.n)).toBe(true)
+ })
+ })
})
)
const get = /*#__PURE__*/ createGetter()
+const shallowReactiveGet = /*#__PURE__*/ createGetter(false, true)
const readonlyGet = /*#__PURE__*/ createGetter(true)
const shallowReadonlyGet = /*#__PURE__*/ createGetter(true, true)
}
const set = /*#__PURE__*/ createSetter()
+const shallowReactiveSet = /*#__PURE__*/ createSetter(false, true)
const readonlySet = /*#__PURE__*/ createSetter(true)
const shallowReadonlySet = /*#__PURE__*/ createSetter(true, true)
}
}
+export const shallowReactiveHandlers: ProxyHandler<object> = {
+ ...mutableHandlers,
+ get: shallowReactiveGet,
+ set: shallowReactiveSet
+}
+
// Props handlers are special in the sense that it should not unwrap top-level
// refs (in order to allow refs to be explicitly passed down), but should
// retain the reactivity of the normal readonly object.
export {
reactive,
isReactive,
+ shallowReactive,
readonly,
isReadonly,
shallowReadonly,
import {
mutableHandlers,
readonlyHandlers,
- shallowReadonlyHandlers
+ shallowReadonlyHandlers,
+ shallowReactiveHandlers
} from './baseHandlers'
import {
mutableCollectionHandlers,
)
}
-// @internal
// Return a reactive-copy of the original object, where only the root level
// properties are readonly, and does NOT unwrap refs nor recursively convert
// returned properties.
)
}
+// Return a reactive-copy of the original object, where only the root level
+// properties are reactive, and does NOT unwrap refs nor recursively convert
+// returned properties.
+export function shallowReactive<T extends object>(target: T): T {
+ return createReactiveObject(
+ target,
+ rawToReactive,
+ reactiveToRaw,
+ shallowReactiveHandlers,
+ mutableCollectionHandlers
+ )
+}
+
function createReactiveObject(
target: unknown,
toProxy: WeakMap<any, any>,