From 14d1c7b3617d100af7a4d2eeec96a41f92c6278b Mon Sep 17 00:00:00 2001 From: ygj6 Date: Fri, 2 Jul 2021 15:52:19 +0800 Subject: [PATCH] fix(shallowReadonly): align behavior with vue-next (#741) --- src/reactivity/readonly.ts | 9 ++++++++- test/v3/reactivity/readonly.spec.ts | 6 ++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/reactivity/readonly.ts b/src/reactivity/readonly.ts index e223c91d..552054ba 100644 --- a/src/reactivity/readonly.ts +++ b/src/reactivity/readonly.ts @@ -1,5 +1,5 @@ import { reactive, Ref, UnwrapRef } from '.' -import { isArray, isPlainObject, warn } from '../utils' +import { isArray, isPlainObject, isObject, warn } from '../utils' import { readonlySet } from '../utils/sets' import { isReactive, observe } from './reactive' import { isRef, RefImpl } from './ref' @@ -49,6 +49,13 @@ export function readonly( export function shallowReadonly(obj: T): Readonly export function shallowReadonly(obj: any): any { + if (!isObject(obj)) { + if (__DEV__) { + warn(`value cannot be made reactive: ${String(obj)}`) + } + return obj + } + if ( !(isPlainObject(obj) || isArray(obj)) || (!Object.isExtensible(obj) && !isRef(obj)) diff --git a/test/v3/reactivity/readonly.spec.ts b/test/v3/reactivity/readonly.spec.ts index 5272f480..a645715e 100644 --- a/test/v3/reactivity/readonly.spec.ts +++ b/test/v3/reactivity/readonly.spec.ts @@ -382,6 +382,12 @@ describe('reactivity/readonly', () => { ).not.toHaveBeenWarned() }) + test('should not process non-object data', () => { + // @ts-ignore + shallowReadonly(25) + expect(`value cannot be made reactive: 25`).toHaveBeenWarned() + }) + // #669 test('shallowReadonly should work for refs', () => { const vm = new Vue({