Skip to content

Commit ea3ad5c

Browse files
authored
fix(shallowReadonly) : shallowReadonly should work for ref. (#704)
1 parent 30e3ddf commit ea3ad5c

File tree

2 files changed

+36
-3
lines changed

2 files changed

+36
-3
lines changed

src/reactivity/readonly.ts

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { reactive, Ref, UnwrapRef } from '.'
22
import { isArray, isPlainObject, warn } from '../utils'
33
import { readonlySet } from '../utils/sets'
4+
import { isRef } from './ref'
45

56
export function isReadonly(obj: any): boolean {
67
return readonlySet.has(obj)
@@ -47,7 +48,10 @@ export function readonly<T extends object>(
4748

4849
export function shallowReadonly<T extends object>(obj: T): Readonly<T>
4950
export function shallowReadonly(obj: any): any {
50-
if (!(isPlainObject(obj) || isArray(obj)) || !Object.isExtensible(obj)) {
51+
if (
52+
!(isPlainObject(obj) || isArray(obj)) ||
53+
(!Object.isExtensible(obj) && !isRef(obj))
54+
) {
5155
return obj
5256
}
5357

@@ -60,7 +64,7 @@ export function shallowReadonly(obj: any): any {
6064
let val = obj[key]
6165
let getter: (() => any) | undefined
6266
const property = Object.getOwnPropertyDescriptor(obj, key)
63-
if (property) {
67+
if (property && !isRef(obj)) {
6468
if (property.configurable === false) {
6569
continue
6670
}

test/v3/reactivity/readonly.spec.ts

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import { mockWarn } from '../../helpers/mockWarn'
2-
import { shallowReadonly, isReactive } from '../../../src'
2+
import { shallowReadonly, isReactive, ref, reactive } from '../../../src'
3+
4+
const Vue = require('vue/dist/vue.common.js')
35

46
// /**
57
// * @see https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html
@@ -372,5 +374,32 @@ describe('reactivity/readonly', () => {
372374
`Set operation on key "foo" failed: target is readonly.`
373375
).not.toHaveBeenWarned()
374376
})
377+
378+
// #669
379+
test('shallowReadonly should work for refs', () => {
380+
const vm = new Vue({
381+
template: '<div>{{ count }} {{ countRef }}</div>',
382+
setup() {
383+
const count = reactive({ number: 0 })
384+
const countRef = ref(0)
385+
386+
const countReadonly = shallowReadonly(count)
387+
const countRefReadonly = shallowReadonly(countRef)
388+
389+
setTimeout(() => {
390+
// @ts-expect-error
391+
countReadonly.number++
392+
// @ts-expect-error
393+
countRefReadonly.value++
394+
}, 2000)
395+
return {
396+
count,
397+
countRef,
398+
}
399+
},
400+
}).$mount()
401+
402+
expect(vm.$el.textContent).toBe(`{\n "number": 0\n} 0`)
403+
})
375404
})
376405
})

0 commit comments

Comments
 (0)