Skip to content

Commit

Permalink
feat: warn when assigning to computed property with no setter
Browse files Browse the repository at this point in the history
close #6078
  • Loading branch information
yyx990803 committed Jul 21, 2017
1 parent a8ac129 commit eb9168c
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 11 deletions.
26 changes: 16 additions & 10 deletions src/core/instance/state.js
Original file line number Diff line number Diff line change
Expand Up @@ -172,18 +172,15 @@ function initComputed (vm: Component, computed: Object) {

for (const key in computed) {
const userDef = computed[key]
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
}
const getter = typeof userDef === 'function' ? userDef : userDef.get
if (process.env.NODE_ENV !== 'production' && getter == null) {
warn(
`Getter is missing for computed property "${key}".`,
vm
)
}
// create internal watcher for the computed property.
watchers[key] = new Watcher(vm, getter, noop, computedWatcherOptions)
watchers[key] = new Watcher(vm, getter || noop, noop, computedWatcherOptions)

// component-defined computed properties are already defined on the
// component prototype. We only need to define computed properties defined
Expand Down Expand Up @@ -214,6 +211,15 @@ export function defineComputed (target: any, key: string, userDef: Object | Func
? userDef.set
: noop
}
if (process.env.NODE_ENV !== 'production' &&
sharedPropertyDefinition.set === noop) {
sharedPropertyDefinition.set = function () {
warn(
`Computed property "${key}" was assigned to but it has no setter.`,
this
)
}
}
Object.defineProperty(target, key, sharedPropertyDefinition)
}

Expand Down
14 changes: 13 additions & 1 deletion test/unit/features/options/computed.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,19 @@ describe('Options computed', () => {
}
}).$mount()
expect(vm.$el.innerHTML).toBe('<div>1</div>')
expect('No getter function has been defined for computed property "b".').toHaveBeenWarned()
expect('Getter is missing for computed property "b".').toHaveBeenWarned()
})

it('warn assigning to computed with no setter', () => {
const vm = new Vue({
computed: {
b () {
return 1
}
}
})
vm.b = 2
expect(`Computed property "b" was assigned to but it has no setter.`).toHaveBeenWarned()
})

it('watching computed', done => {
Expand Down

0 comments on commit eb9168c

Please sign in to comment.