【问题标题】:Set data object in vuejs using axios response [duplicate]使用axios响应在vuejs中设置数据对象[重复]
【发布时间】:2018-06-11 13:37:37
【问题描述】:

我正在进行 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; 不是。有什么想法吗?

【问题讨论】:

标签: javascript vue.js vuejs2 axios


【解决方案1】:

您的 catch 处理程序中的 this 值不是您所期望的。解决该问题的最简单方法是使用箭头函数,例如 .catch(error => { this.errors = error.response.data.error; })

如果您的环境不允许 ES6 功能,您可以改用Function.bind(this)

【讨论】:

    猜你喜欢
    • 2017-06-21
    • 2018-02-16
    • 2020-03-22
    • 1970-01-01
    • 1970-01-01
    • 2022-12-20
    • 2018-07-25
    • 1970-01-01
    • 2019-08-07
    相关资源
    最近更新 更多