当我在types
方法中收到响应时,我试图设置一个名为ready()
的数据对象。
这样地:
export default {
data () {
return {
types: null
}
},
ready () {
TypeService.showAll(1)
.then(function(data) {
this.types = data.types
});
}
}
但我在控制台中收到以下错误:
Cannot set property 'types' of undefined(…)
但是当我像这样console.log时:
ready () {
TypeService.showAll(1)
.then(function(data) {
console.log(data);
});
}
不是空的!?!是吗?
这是怎么回事?它让我发疯。
--编辑--
TypeService.showAll(1)
.then(({ data }) => ({
this.types: data.types
}.bind(this)));
最佳答案
问题是this.types
,而不是data.types
(JS错误消息不完全清楚)。
ready () {
TypeService.showAll(1)
.then(function(data) {
this.types = data.types
});
}
this
不是您在这里的function
中所期望的(它不是vue组件)。这应该可以做到: ready () {
TypeService.showAll(1)
.then(function(data) {
this.types = data.types
}.bind(this));
}