]> git.ipfire.org Git - thirdparty/vuejs/core.git/commitdiff
feat(apiOptions): warn invalid computed options (#225)
authorCr <631807682@qq.com>
Mon, 14 Oct 2019 06:15:31 +0000 (14:15 +0800)
committerEvan You <yyx990803@gmail.com>
Mon, 14 Oct 2019 06:15:31 +0000 (02:15 -0400)
packages/runtime-core/__tests__/apiOptions.spec.ts
packages/runtime-core/src/apiOptions.ts

index 8c3fbdf24c759cb50ccc7b1ec4594e3a1c9f040e..656f1c36d4b5354d6fc9022f1e4ab6dbed7df5a5 100644 (file)
@@ -538,5 +538,42 @@ describe('api: options', () => {
 
       expect('Invalid watch option: "foo"').toHaveBeenWarned()
     })
+
+    test('computed with setter and no getter', () => {
+      const Comp = {
+        computed: {
+          foo: {
+            set() {}
+          }
+        },
+        render() {}
+      }
+
+      const root = nodeOps.createElement('div')
+      render(h(Comp), root)
+      expect('Computed property "foo" has no getter.').toHaveBeenWarned()
+    })
+
+    test('assigning to computed with no setter', () => {
+      let instance: any
+      const Comp = {
+        computed: {
+          foo: {
+            get() {}
+          }
+        },
+        mounted() {
+          instance = this
+        },
+        render() {}
+      }
+
+      const root = nodeOps.createElement('div')
+      render(h(Comp), root)
+      instance.foo = 1
+      expect(
+        'Computed property "foo" was assigned to but it has no setter.'
+      ).toHaveBeenWarned()
+    })
   })
 })
index fe91d300233a6a3f22b522d4a9eed5afe907eb94..6b0fce58470908db7c5c05b42ede86fa27405be0 100644 (file)
@@ -10,7 +10,8 @@ import {
   isString,
   isObject,
   isArray,
-  EMPTY_OBJ
+  EMPTY_OBJ,
+  NOOP
 } from '@vue/shared'
 import { computed } from './apiReactivity'
 import { watch, WatchOptions, CleanupRegistrator } from './apiWatch'
@@ -245,12 +246,28 @@ export function applyOptions(
   if (computedOptions) {
     for (const key in computedOptions) {
       const opt = (computedOptions as ComputedOptions)[key]
-      renderContext[key] = isFunction(opt)
-        ? computed(opt.bind(ctx))
-        : computed({
-            get: opt.get.bind(ctx),
-            set: opt.set.bind(ctx)
+
+      if (isFunction(opt)) {
+        renderContext[key] = computed(opt.bind(ctx))
+      } else {
+        const { get, set } = opt
+        if (isFunction(get)) {
+          renderContext[key] = computed({
+            get: get.bind(ctx),
+            set: isFunction(set)
+              ? set.bind(ctx)
+              : __DEV__
+                ? () => {
+                    warn(
+                      `Computed property "${key}" was assigned to but it has no setter.`
+                    )
+                  }
+                : NOOP
           })
+        } else if (__DEV__) {
+          warn(`Computed property "${key}" has no getter.`)
+        }
+      }
     }
   }
   if (methods) {