首页 > 解决方案 > 在 axios 发布响应后,Vue 实例中的数据不会更新

问题描述

我正在编写一段代码来在 POST REST API 上提交 html 表单数据。为此使用 Vue.js 和 axios。

我的 Vue.js 代码是这样的——

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

)

和 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>

此代码不会更新 responseText。我可以在浏览器中签入 Vue 插件。知道我的例子中有什么不正确的吗?

标签: vue.jsvuejs2axios

解决方案


您需要在回调中使用箭头函数,否则该函数会注入自己的this上下文:

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

或者你可以使用异步/等待:

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

推荐阅读