]> git.ipfire.org Git - thirdparty/vuejs/core.git/commitdiff
feat(computed): add readonly flag if no setter is provided (#1654)
authorCarlos Rodrigues <david-181@hotmail.com>
Mon, 20 Jul 2020 21:35:31 +0000 (22:35 +0100)
committerGitHub <noreply@github.com>
Mon, 20 Jul 2020 21:35:31 +0000 (17:35 -0400)
packages/reactivity/__tests__/computed.spec.ts
packages/reactivity/src/computed.ts

index 5ab4641e98878e153117be16775c1df76e017a38..fe6161ff881d40bce0a2851386fbe076825251fe 100644 (file)
@@ -4,7 +4,8 @@ import {
   effect,
   stop,
   ref,
-  WritableComputedRef
+  WritableComputedRef,
+  isReadonly
 } from '../src'
 import { mockWarn } from '@vue/shared'
 
@@ -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)
+  })
 })
index 9aa7c6cf7f49d0e34fc703a0487f47ca97c4c25d..32740f983b1acbeb8c762f15d4d124270085654d 100644 (file)
@@ -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
@@ -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() {