Vuejs2 Can';Vue JS中Axios promise内部的t set属性

Vuejs2 Can';Vue JS中Axios promise内部的t set属性,vuejs2,vue.js,Vuejs2,Vue.js,我尝试使用VueJS和Axios向Laravel后端发出HTTP请求,以获取一些JSON,然后使用JSON更新组件上的errorMessage属性 Axios.post('/api/login', { email: this.email, password: this.password }).then((response) => { this.er

我尝试使用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);
            })
问题是它无法引用此.errorMessage出于某种原因,我在这里做错了什么吗?我正确地发出HTTP请求,如果我
console.log
它,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的调试器,它向我显示了
未定义的值,即使它们不是。。。对于这个愚蠢的问题,我很抱歉,我希望这将帮助其他遇到此类问题的人。

响应的数据位于
数据属性下:

this.errorMessage=response.data.message;

Axios.post是closer函数,因此它中的属性定义看起来像closer函数下的private

您必须在closer外部定义变量,如下所示:

//this will pick your data.
let self = this;


Axios.post('/api/login', {
     email: this.email,
     password: this.password
  }).then((response) => {
  self.errorMessage = response.message;
            }).catch((error) => {
                console.error(error);
            })

另外,如果
response.message
未定义,则使用
response.body.message
或laravel返回的变量

这是一个背景问题。显示更多代码。@JonatasWalker我已经用这个特定组件的完整代码更新了问题。Hi Joseph可能重复,问题是
this.errorMessage
未定义,所以它将字符串设置为未定义,所以它什么也不做。我不太清楚为什么这个.errorMessage是未定义的,因为我使用的是胖箭头函数。。。我可能被这里的某些东西弄糊涂了。@JoãoSerra-它是
未定义的
,因为
响应。消息
未定义的
。改为使用
response.data.message
。我做了,我正在使用
debugger
检查值它不再是未定义的,但问题仍然存在,就像Jonatas Walker注意到这是一个上下文问题一样,我只是不完全确定如何修复它。是的。这就是@MandeepGill谢谢:)出于某种原因,当我将鼠标悬停在self.errorMessage上时,chrome中的调试器不断地说它是
未定义的
,这完全把我甩了,因为我以前确实试过。但是,尽管Chrome说它是未定义的,但它仍然可以工作。可能你有一个缓存,在Chrome中,开发者工具中有一个网络选项卡打开,该选项卡检查禁用缓存并保持开发者工具打开,然后刷新,如果这个问题仍然存在,请告诉我。这个答案是错误的。这正是箭头函数的用途;他们保留了外部环境。@JosephSilber你说得对。。。是该死的调试器。。。很抱歉