Pārlūkot izejas kodu

warn and handle missing get in computed (fix #5265) (#5267)

Kenneth Crawford 9 gadi atpakaļ
vecāks
revīzija
6fcfdbd83f

+ 10 - 1
src/core/instance/state.js

@@ -147,7 +147,16 @@ function initComputed (vm: Component, computed: Object) {
 
 
   for (const key in computed) {
   for (const key in computed) {
     const userDef = computed[key]
     const userDef = computed[key]
-    const getter = typeof userDef === 'function' ? userDef : userDef.get
+    let getter = typeof userDef === 'function' ? userDef : userDef.get
+    if (process.env.NODE_ENV !== 'production') {
+      if (getter === undefined) {
+        warn(
+          `No getter function has been defined for computed property "${key}".`,
+          vm
+        )
+        getter = noop
+      }
+    }
     // create internal watcher for the computed property.
     // create internal watcher for the computed property.
     watchers[key] = new Watcher(vm, getter, noop, computedWatcherOptions)
     watchers[key] = new Watcher(vm, getter, noop, computedWatcherOptions)
 
 

+ 27 - 0
test/unit/features/options/computed.spec.js

@@ -48,6 +48,33 @@ describe('Options computed', () => {
     }).then(done)
     }).then(done)
   })
   })
 
 
+  it('warn with setter and no getter', () => {
+    const vm = new Vue({
+      template: `
+        <div>
+          <test></test>
+        </div>
+      `,
+      components: {
+        test: {
+          data () {
+            return {
+              a: 1
+            }
+          },
+          computed: {
+            b: {
+              set (v) { this.a = v }
+            }
+          },
+          template: `<div>{{a}}</div>`
+        }
+      }
+    }).$mount()
+    expect(vm.$el.innerHTML).toBe('<div>1</div>')
+    expect('No getter function has been defined for computed property "b".').toHaveBeenWarned()
+  })
+
   it('watching computed', done => {
   it('watching computed', done => {
     const spy = jasmine.createSpy('watch computed')
     const spy = jasmine.createSpy('watch computed')
     const vm = new Vue({
     const vm = new Vue({