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

Joã*_*rra 2 vue.js vuejs2

我正在尝试使用VueJS和Axios向Laravel后端发出HTTP请求以获取一些JSON,然后使用JSON更新我的Component上的errorMessage属性.

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

问题是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
    }
}   
Run Code Online (Sandbox Code Playgroud)

解:

原始请求是正确的,胖箭头函数应该保持值this,问题出在Chrome的调试器上,它显示了我的价值,undefined即使它们不是......抱歉这个愚蠢的问题,我希望这会有助于其他人们遇到这种问题.

Man*_*ill 11

Axios.post是更接近的函数,因此属性在其中定义看起来像私密的更近的功能.

你必须像这样更接近地定义变量:

//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);
            })
Run Code Online (Sandbox Code Playgroud)

如果response.message未定义,则使用response.body.messagelaravel中的或返回变量.