Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
410 views
in Technique[技术] by (71.8m points)

vue.js - data in Vue instance doesn't get updated after axios post response

I am writing a code piece to submit the html form data on a POST REST API. Using Vue.js and axios for that.

My Vue.js code is like this -

const app = new Vue({
    el: "#main-div",
    data() { return {
        name: 'Please enter the name',
        showEdit: true,
        showResponse: true,
        responseText: null
    }
    },
    methods: {
         savePerson: function () {
           this.showEdit = false;
           axios
            .post('/api/person', {
                name: this.name
              })
              .then(function (response) {
                this.responseText = response.data.name+ ' added successfully.';
                console.log(response);
                console.log(response.data.name+ ' added successfully.');
              })
              .catch(function (error) {
                this.responseText = error.message;
                console.log(error);
              });
         }
    }
}

)

And html -

<div id="main-div">
<h2> Fill out the details to create a Person</h2>
<div v-if="showEdit">
    <form >
        <div>
            Name: <input v-bind:value = 'name' type="text" v-on:focus="name= ''" />
        </div>
        
        <div>
            <button v-on:click="savePerson">Save</button>
        </div>
    </form>
</div>
<div v-if="showResponse">
    <div><p>{{ responseText }}</p></div>
    <div>
        <button v-on:click="showEdit = true">Add one more person</button>
    </div>
</div>

This code doesn't update responseText. That I can check in Vue plugin in browser. Any idea what is not correct in my example?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to use an arrow function in the callback or else the function injects its own this context:

.then((response) => {
...
})
.catch((error) => {
...
})

Or you could use async/await:

async savePerson() {
  this.showEdit = false;
  try {
    const response = await axios.post('/api/person', {
      name: this.name
    })
    this.responseText = response.data.name+ ' added successfully.';
  } catch(error) {
    this.responseText = error.message;
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...