【问题标题】:Can't set property inside of Axios promise in Vue JS无法在 Vue JS 中的 Axios 承诺内设置属性
【发布时间】: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,即使它们不是......抱歉愚蠢的问题,我希望这会帮助其他人遇到这种问题。

【问题讨论】:

标签: vuejs2 vue.js


【解决方案1】:

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);
            })

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

【讨论】:

  • 是的。就是这样@MandeepGill 谢谢你:) 出于某种原因,当我将鼠标悬停在self.errorMessage 上时,chrome 中的调试器一直说它是undefined,这完全让我失望了,因为我之前实际上已经尝试过。但尽管 Chrome 说它是 undefined,但它无论如何都可以工作。
  • 您可能有缓存,在 chrome 中,开发人员工具中有网络选项卡打开该选项卡检查禁用缓存并保持开发人员工具打开,然后刷新并让我知道这个问题是否仍然存在。
  • 这个答案是错误的。这正是箭头函数的用途;他们保留外部上下文。
  • @JosephSilber 你是对的......这是该死的调试器......对不起
【解决方案2】:

响应的数据在data 属性下可用:

this.errorMessage = response.data.message;

【讨论】:

  • 嗨约瑟夫,问题是this.errorMessage 是未定义的,所以它将一个字符串设置为未定义,所以它什么都不做。我不太清楚为什么 this.errorMessage 是未定义的,因为我使用的是胖箭头函数......我可能会与这里的某些东西混淆。
  • @JoãoSerra - 这是undefined,因为response.messageundefined。请改用response.data.message
  • 我做到了,我正在使用 debugger 检查它不再未定义的值,但问题仍然存在,就像 Jonatas Walker 注意到它肯定是一个上下文问题,我只是不完全确定如何解决它。
猜你喜欢
  • 2017-09-22
  • 1970-01-01
  • 2020-01-01
  • 2019-08-14
  • 2017-09-27
  • 2020-08-08
  • 1970-01-01
  • 2019-04-07
相关资源
最近更新 更多