【问题标题】:My Vue.js code about Axios and function is not working我关于 Axios 和功能的 Vue.js 代码不起作用
【发布时间】:2019-06-07 20:55:45
【问题描述】:

我想在 axios 之后执行 function2。我没有捕获错误。但仍然没有执行 Function2。

我想要但不起作用的代码:

   add: function () {
        axios.post('/add', this.person)
            .then(response => {
               if (response.data.etat) {
                    this.person = {};
                    this.function2();
                }
            })
            .catch(error => {
                console.log('errors: ', error)
            })},

这是可行的,但我只想在 axios 通过时执行 function2。

add: function () {
        axios.post('/add', this.person)
            .then(response => {
               if (response.data.etat) {
                    this.person = {};

                }
            })
            .catch(error => {
                console.log('errors: ', error)
            })
             this.function2();
             },

有什么帮助吗?谢谢 !

【问题讨论】:

  • response.data.etat 返回什么?
  • 什么都没有.. 但是我的 axios 通过并且我的数据被发送到数据库

标签: javascript vue.js vuejs2 axios vue-component


【解决方案1】:

您可以链接 .then() 块:

add: function () {
        axios.post('/add', this.person)
            .then(response => {
               if (response.data.etat) {
                    this.person = {};
                }
            })
            .then(() => {
               this.function2();
            })
            .catch(error => {
                console.log('errors: ', error)
            })
}

this.function2 只有在你的 axios.post 成功并且第一个 .then() 没有抛出任何错误时才会被调用。在另一种情况下 - 您的 .catch() 将捕获错误。

在这里你可以看到它是如何在现场工作的: https://codepen.io/anon/pen/gZQyym?editors=1111

【讨论】:

    【解决方案2】:

    由于您使用 axios 发布数据,并且您希望在操作成功完成后调用该方法,因此您应该检查响应状态,例如:

       add: function () {
        axios.post('/add', this.person)
            .then(response => {
               if (response.status==200) {
                    this.person = {};
                    this.function2();
                }
            })
            .catch(error => {
                console.log('errors: ', error)
            })},
    

    【讨论】:

    • 感谢您的关注!顺便说一句,我是 Y.J
    • :) 我猜到了
    猜你喜欢
    • 1970-01-01
    • 2016-03-23
    • 2021-01-07
    • 2018-05-13
    • 1970-01-01
    • 2017-12-12
    • 2016-08-09
    • 2020-10-21
    • 1970-01-01
    相关资源
    最近更新 更多