简体   繁体   中英

My Vue.js code about Axios and function is not working

I want to execute function2 after axios. I got no catch error. but still Function2 is not executed.

The code i want but not working :

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

This is working, but i would like to execute function2 only if axios pass.

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

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

Any help ? thank you !

You can chain .then() blocks:

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 will be called only if your axios.post is successful and if the first .then() doesn't throw any error. In another case - your .catch() will catch the error.

Here you can see how it works on live: https://codepen.io/anon/pen/gZQyym?editors=1111

Since you're using axios to post data, and you want to do call that method after the operation is done successfully so you should check the response status like :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM