Skip to content

Commit

Permalink
feat(computed): add readonly flag if no setter is provided (#1654)
Browse files Browse the repository at this point in the history
  • Loading branch information
pikax committed Jul 20, 2020
1 parent ad199e1 commit dabdc5e
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
21 changes: 20 additions & 1 deletion packages/reactivity/__tests__/computed.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ import {
effect,
stop,
ref,
WritableComputedRef
WritableComputedRef,
isReadonly
} from '../src'
import { mockWarn } from '@vue/shared'

Expand Down Expand Up @@ -177,4 +178,22 @@ describe('reactivity/computed', () => {
'Write operation failed: computed value is readonly'
).toHaveBeenWarnedLast()
})

it('should be readonly', () => {
let a = { a: 1 }
const x = computed(() => a)
expect(isReadonly(x)).toBe(true)
expect(isReadonly(x.value)).toBe(false)
expect(isReadonly(x.value.a)).toBe(false)
const z = computed<typeof a>({
get() {
return a
},
set(v) {
a = v
}
})
expect(isReadonly(z)).toBe(false)
expect(isReadonly(z.value.a)).toBe(false)
})
})
4 changes: 4 additions & 0 deletions packages/reactivity/src/computed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { effect, ReactiveEffect, trigger, track } from './effect'
import { TriggerOpTypes, TrackOpTypes } from './operations'
import { Ref } from './ref'
import { isFunction, NOOP } from '@vue/shared'
import { ReactiveFlags } from './reactive'

export interface ComputedRef<T = any> extends WritableComputedRef<T> {
readonly value: T
Expand Down Expand Up @@ -56,6 +57,9 @@ export function computed<T>(
})
computed = {
__v_isRef: true,
[ReactiveFlags.IS_READONLY]:
isFunction(getterOrOptions) || !getterOrOptions.set,

// expose effect so computed can be stopped
effect: runner,
get value() {
Expand Down

0 comments on commit dabdc5e

Please sign in to comment.