【发布时间】:2017-02-21 14:12:21
【问题描述】:
我正在尝试使用 VueJS 和 Axios 向 Laravel 后端发出 HTTP 请求以获取一些 JSON,然后使用 JSON 更新我的组件上的 errorMessage 属性。
Axios.post('/api/login', {
email: this.email,
password: this.password
}).then((response) => {
this.errorMessage = response.message;
}).catch((error) => {
console.error(error);
})
问题是由于某种原因它无法引用this.errorMessage,我在这里做错了吗?如果我 console.log 它,我正确地发出了 HTTP 请求,并且 JSON 响应按预期返回,但是当我尝试操纵 this.errorMessage 时,它说它是未定义的,即使我已经在其他地方成功地操纵了它。 ..
这是该组件的完整代码
export default {
methods: {
submitForm: function(e) {
e.preventDefault();
Axios.post('/api/login', {
email: this.email,
password: this.password
}).then((response) => {
debugger;
this.errorMessage = response.data.message;
}).catch((error) => {
console.error(error);
});
}
},
data: function() {
return {
errorMessage: null,
email: null,
password: null
}
},
components: {
'error': Error
}
}
解决方案:
原始请求是正确的,粗箭头函数应该保持 this 的值,问题出在 Chrome 的调试器上,它向我显示的值是 undefined,即使它们不是......抱歉愚蠢的问题,我希望这会帮助其他人遇到这种问题。
【问题讨论】:
-
这是一个上下文问题。显示更多代码。
-
@JonatasWalker 我已经用这个特定组件的整个代码更新了这个问题。