From: Dmitry Sharshakov Date: Wed, 9 Oct 2019 16:20:53 +0000 (+0300) Subject: feat(computed): warn if trying to set a readonly computed (#161) X-Git-Tag: v3.0.0-alpha.0~536 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=530be302fc8ea4fc7246246096077660fb3ee6a3;p=thirdparty%2Fvuejs%2Fcore.git feat(computed): warn if trying to set a readonly computed (#161) --- diff --git a/packages/reactivity/__tests__/computed.spec.ts b/packages/reactivity/__tests__/computed.spec.ts index a9199f554c..0ab644af7f 100644 --- a/packages/reactivity/__tests__/computed.spec.ts +++ b/packages/reactivity/__tests__/computed.spec.ts @@ -1,6 +1,16 @@ -import { computed, reactive, effect, stop, ref } from '../src' +import { + computed, + reactive, + effect, + stop, + ref, + WritableComputedRef +} from '../src' +import { mockWarn } from '@vue/runtime-test' describe('reactivity/computed', () => { + mockWarn() + it('should return updated value', () => { const value = reactive<{ foo?: number }>({}) const cValue = computed(() => value.foo) @@ -157,4 +167,14 @@ describe('reactivity/computed', () => { plusOne.value = 0 expect(dummy).toBe(-1) }) + + it('should warn if trying to set a readonly computed', () => { + const n = ref(1) + const plusOne = computed(() => n.value + 1) + ;(plusOne as WritableComputedRef).value++ // Type cast to prevent TS from preventing the error + + expect( + 'Write operation failed: computed value is readonly' + ).toHaveBeenWarnedLast() + }) }) diff --git a/packages/reactivity/src/computed.ts b/packages/reactivity/src/computed.ts index 4e11b7c754..b505e30157 100644 --- a/packages/reactivity/src/computed.ts +++ b/packages/reactivity/src/computed.ts @@ -29,7 +29,9 @@ export function computed( : (getterOrOptions as WritableComputedOptions).get const setter = isReadonly ? () => { - // TODO warn attempting to mutate readonly computed value + if (__DEV__) { + console.warn('Write operation failed: computed value is readonly') + } } : (getterOrOptions as WritableComputedOptions).set