我正在进行 API 调用并收到(预期的)错误。我可以控制台记录错误消息,但我似乎无法使用响应设置 vuejs 数据变量。我做错了什么?
data: {
...
...
errors: null
},
methods: {
checkConnections: function (event) {
axios.post('/checkconnections', {
//form data is passed here
...
...
})
.then(function (response) {
console.log(response);
}).catch(function (error) {
console.log(error.response.data.error);
this.errors = error.response.data.error;
});
}
}
console.log(error.response.data.error)
部分工作正常,但作业 this.errors = error.response.data.error;
不是。有什么想法吗?
最佳答案
catch 处理程序中的 this
值不是您所期望的。解决该问题的最简单方法是使用箭头函数,例如 .catch(error => { this.errors = error.response.data.error; })
。
如果您的环境不允许 ES6 功能,您可以使用 Function.bind(this)相反。
关于javascript - 使用 axios 响应在 vuejs 中设置数据对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50799081/