无法在 Vue JS 中的 Axios 承诺中设置 属性

Can't set property inside of Axios promise in Vue JS

我正在尝试使用 VueJS 和 Axios 向 Laravel 后端发出 HTTP 请求以获取一些 JSON 然后使用 JSON 更新错误消息 属性 在我的组件上。

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

问题是由于某种原因无法引用 this.errorMessage,我是不是做错了什么?我正确地发出了 HTTP 请求,并且 JSON 响应如预期的那样返回,如果我 console.log 它,但是当我尝试操作 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即使他们不是...抱歉这个愚蠢的问题,我希望这会帮助其他人遇到此类问题。

响应的数据在 data 属性:

下可用
this.errorMessage = response.data.message;

Axios.post 是 closer 函数,因此 属性 在其中定义在 closer 函数下看起来像是私有的。

你必须像这样在 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 的返回变量。