Skip to content

Commit

Permalink
fix(shallowReadonly) : shallowReadonly should work for ref. (#704)
Browse files Browse the repository at this point in the history
  • Loading branch information
ygj6 committed May 27, 2021
1 parent 30e3ddf commit ea3ad5c
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 3 deletions.
8 changes: 6 additions & 2 deletions src/reactivity/readonly.ts
@@ -1,6 +1,7 @@
import { reactive, Ref, UnwrapRef } from '.'
import { isArray, isPlainObject, warn } from '../utils'
import { readonlySet } from '../utils/sets'
import { isRef } from './ref'

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

export function shallowReadonly<T extends object>(obj: T): Readonly<T>
export function shallowReadonly(obj: any): any {
if (!(isPlainObject(obj) || isArray(obj)) || !Object.isExtensible(obj)) {
if (
!(isPlainObject(obj) || isArray(obj)) ||
(!Object.isExtensible(obj) && !isRef(obj))
) {
return obj
}

Expand All @@ -60,7 +64,7 @@ export function shallowReadonly(obj: any): any {
let val = obj[key]
let getter: (() => any) | undefined
const property = Object.getOwnPropertyDescriptor(obj, key)
if (property) {
if (property && !isRef(obj)) {
if (property.configurable === false) {
continue
}
Expand Down
31 changes: 30 additions & 1 deletion test/v3/reactivity/readonly.spec.ts
@@ -1,5 +1,7 @@
import { mockWarn } from '../../helpers/mockWarn'
import { shallowReadonly, isReactive } from '../../../src'
import { shallowReadonly, isReactive, ref, reactive } from '../../../src'

const Vue = require('vue/dist/vue.common.js')

// /**
// * @see https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html
Expand Down Expand Up @@ -372,5 +374,32 @@ describe('reactivity/readonly', () => {
`Set operation on key "foo" failed: target is readonly.`
).not.toHaveBeenWarned()
})

// #669
test('shallowReadonly should work for refs', () => {
const vm = new Vue({
template: '<div>{{ count }} {{ countRef }}</div>',
setup() {
const count = reactive({ number: 0 })
const countRef = ref(0)

const countReadonly = shallowReadonly(count)
const countRefReadonly = shallowReadonly(countRef)

setTimeout(() => {
// @ts-expect-error
countReadonly.number++
// @ts-expect-error
countRefReadonly.value++
}, 2000)
return {
count,
countRef,
}
},
}).$mount()

expect(vm.$el.textContent).toBe(`{\n "number": 0\n} 0`)
})
})
})

0 comments on commit ea3ad5c

Please sign in to comment.