问 题
刚开始学Vue.js,写了个demo,提示:
The "data" option should be a function that returns a per-instance value in component definitions.
但是我看文档里出现的data都是一个对象,比如:
var vm = new Vue({
data: {
a: 1
},
created: function () {
// `this` 指向 vm 实例
console.log('a is: ' + this.a)
}
})
// -> "a is: 1"
解决方案
我猜你会得出警告是在子组件里用对象形式声明了data吧?源码里有这样的判断:
strats.data = function (parentVal, childVal, vm) {
if (!vm) {
// in a Vue.extend merge, both should be functions
if (!childVal) {
return parentVal
}
//注意这个部分!!!!!!!
if (typeof childVal !== 'function') {
process.env.NODE_ENV !== 'production' && warn(
'The "data" option should be a function ' +
'that returns a per-instance value in component ' +
'definitions.',
vm
)
return parentVal
}
if (!parentVal) {
return childVal
}
...
...
然后再来看组件文档,其实文档里基本有了,只是没放大,标红而已^^.我之前也没注意到|_|
扫一扫关注IT屋
微信公众号搜索 “ IT屋 ” ,选择关注与百万开发者在一起