vue.js - 在 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 插件。知道我的例子中有什么不正确的吗?
解决方案
您需要在回调中使用箭头函数,否则该函数会注入自己的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;
}
}
推荐阅读
- javascript - 在 javascript 待办事项应用程序中制作计数器
- file - 如何使用 Flask 在浏览器中打开文件
- java - 派生类的spring bean验证很慢
- amazon-web-services - 如何在 EC2 实例上运行 tensorflow 程序,同时保持免费套餐
- javascript - 为 .includes 添加了 poly-fill,但在一个区域仍然出现错误,尽管在所有其他区域都已解决
- git - 通过 VPN 使用时 Git 命令停止
- php - 使用 .htacess 不允许直接 url 访问文件
- python-3.x - 使用 BigQuery / Python3 / Reddit “项目名称需要用点分隔”错误
- mongodb - 从 Spark 写入 Mongo 副本集(在 Scala 中)
- windbg - 如何通过 CLRMD 获取 WinDBG 中显示的异常