Skip to content

Commit eb9168c

Browse files
committed
feat: warn when assigning to computed property with no setter
close #6078
1 parent a8ac129 commit eb9168c

File tree

2 files changed

+29
-11
lines changed

2 files changed

+29
-11
lines changed

Diff for: src/core/instance/state.js

+16-10
Original file line numberDiff line numberDiff line change
@@ -172,18 +172,15 @@ function initComputed (vm: Component, computed: Object) {
172172

173173
for (const key in computed) {
174174
const userDef = computed[key]
175-
let getter = typeof userDef === 'function' ? userDef : userDef.get
176-
if (process.env.NODE_ENV !== 'production') {
177-
if (getter === undefined) {
178-
warn(
179-
`No getter function has been defined for computed property "${key}".`,
180-
vm
181-
)
182-
getter = noop
183-
}
175+
const getter = typeof userDef === 'function' ? userDef : userDef.get
176+
if (process.env.NODE_ENV !== 'production' && getter == null) {
177+
warn(
178+
`Getter is missing for computed property "${key}".`,
179+
vm
180+
)
184181
}
185182
// create internal watcher for the computed property.
186-
watchers[key] = new Watcher(vm, getter, noop, computedWatcherOptions)
183+
watchers[key] = new Watcher(vm, getter || noop, noop, computedWatcherOptions)
187184

188185
// component-defined computed properties are already defined on the
189186
// component prototype. We only need to define computed properties defined
@@ -214,6 +211,15 @@ export function defineComputed (target: any, key: string, userDef: Object | Func
214211
? userDef.set
215212
: noop
216213
}
214+
if (process.env.NODE_ENV !== 'production' &&
215+
sharedPropertyDefinition.set === noop) {
216+
sharedPropertyDefinition.set = function () {
217+
warn(
218+
`Computed property "${key}" was assigned to but it has no setter.`,
219+
this
220+
)
221+
}
222+
}
217223
Object.defineProperty(target, key, sharedPropertyDefinition)
218224
}
219225

Diff for: test/unit/features/options/computed.spec.js

+13-1
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,19 @@ describe('Options computed', () => {
7575
}
7676
}).$mount()
7777
expect(vm.$el.innerHTML).toBe('<div>1</div>')
78-
expect('No getter function has been defined for computed property "b".').toHaveBeenWarned()
78+
expect('Getter is missing for computed property "b".').toHaveBeenWarned()
79+
})
80+
81+
it('warn assigning to computed with no setter', () => {
82+
const vm = new Vue({
83+
computed: {
84+
b () {
85+
return 1
86+
}
87+
}
88+
})
89+
vm.b = 2
90+
expect(`Computed property "b" was assigned to but it has no setter.`).toHaveBeenWarned()
7991
})
8092

8193
it('watching computed', done => {

0 commit comments

Comments
 (0)