Skip to content

Commit a18f879

Browse files
committed
warn when methods conflict with data (close #5832)
1 parent 7b06945 commit a18f879

File tree

2 files changed

+26
-4
lines changed

2 files changed

+26
-4
lines changed

src/core/instance/state.js

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -130,16 +130,26 @@ function initData (vm: Component) {
130130
// proxy data on instance
131131
const keys = Object.keys(data)
132132
const props = vm.$options.props
133+
const methods = vm.$options.methods
133134
let i = keys.length
134135
while (i--) {
135-
if (props && hasOwn(props, keys[i])) {
136+
const key = keys[i]
137+
if (process.env.NODE_ENV !== 'production') {
138+
if (methods && hasOwn(methods, key)) {
139+
warn(
140+
`method "${key}" has already been defined as a data property.`,
141+
vm
142+
)
143+
}
144+
}
145+
if (props && hasOwn(props, key)) {
136146
process.env.NODE_ENV !== 'production' && warn(
137-
`The data property "${keys[i]}" is already declared as a prop. ` +
147+
`The data property "${key}" is already declared as a prop. ` +
138148
`Use prop default value instead.`,
139149
vm
140150
)
141-
} else if (!isReserved(keys[i])) {
142-
proxy(vm, `_data`, keys[i])
151+
} else if (!isReserved(key)) {
152+
proxy(vm, `_data`, key)
143153
}
144154
}
145155
// observe data

test/unit/features/options/methods.spec.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,4 +27,16 @@ describe('Options methods', () => {
2727
})
2828
expect(`method "hello" has an undefined value in the component definition`).toHaveBeenWarned()
2929
})
30+
31+
it('should warn methods conflicting with data', () => {
32+
new Vue({
33+
data: {
34+
foo: 1
35+
},
36+
methods: {
37+
foo () {}
38+
}
39+
})
40+
expect(`method "foo" has already been defined as a data property`).toHaveBeenWarned()
41+
})
3042
})

0 commit comments

Comments
 (0)