]> git.ipfire.org Git - thirdparty/vuejs/core.git/commitdiff
feat(computed): warn if trying to set a readonly computed (#161)
authorDmitry Sharshakov <d3dx12.xx@gmail.com>
Wed, 9 Oct 2019 16:20:53 +0000 (19:20 +0300)
committerEvan You <yyx990803@gmail.com>
Wed, 9 Oct 2019 16:20:53 +0000 (12:20 -0400)
packages/reactivity/__tests__/computed.spec.ts
packages/reactivity/src/computed.ts

index a9199f554c1709736e76a846352241c2c3e7ebbd..0ab644af7f164d2d32457176b9e6b79585596046 100644 (file)
@@ -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<number>).value++ // Type cast to prevent TS from preventing the error
+
+    expect(
+      'Write operation failed: computed value is readonly'
+    ).toHaveBeenWarnedLast()
+  })
 })
index 4e11b7c754041f07ae0a3ccdd1bb85394c32f539..b505e30157e14602d71101002417cec11cd38b79 100644 (file)
@@ -29,7 +29,9 @@ export function computed<T>(
     : (getterOrOptions as WritableComputedOptions<T>).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<T>).set