javascript - 如何使用 vue.js 从 Promise 中的方法更新数据值?
问题描述
我的组件脚本是:
export default {
name: "Authenticate",
data: () => {
return {
validationFailed: {}
};
},
methods: {
validateForm() {
this.validationFailed = {};
if (this.createEmail.trim().length === 0) {
this.validationFailed.createEmailField = "Email cannot be blank. ";
}
if (this.createPassword.trim().length === 0) {
this.validationFailed.createPasswordField =
"Password cannot be blank. ";
}
if (Object.keys(this.validationFailed).length === 0) {
return true;
}
return false;
},
handleSubmit() {
const that = this;
axios
.request({
url: `${process.env.VUE_APP_API_URL}/users`,
method: "POST",
data: {
email: this.createEmail,
password: this.createPassword
}
})
.then(response => {
console.log(response);
})
.catch(err => {
that.validationFailed.createEmailField = "something";
});
}
}
};
但是在 catch 里面debugger
,我可以看到值被设置了。但在我template
的 中,validationFailed
没有更新。我究竟做错了什么?
解决方案
这是 Vue 反应性问题。您需要分配this.validationFailed
给新对象。您可以在 catch 块中尝试 ES6 语法:
that.validationFailed = {
...that.validationFailed,
createEmailField: 'something'
}
推荐阅读
- java - 开发 SDK 时隐藏实现
- gerrit - gerrit:无法访问设置页面
- node.js - 即使您输入有效命令,仍会弹出未知命令消息
- javascript - 使用 const 值作为联合类型选项
- c++ - QTabBar设置为东或西时如何设置图标?
- javascript - Node.js - 读取流返回 ENOENT(errornr #4058)
- react-bootstrap-typeahead - onChange 事件清除输入
- ruby-on-rails - 从 rails 5.1.7 中的资产管道迁移后,无法使用 webpacker 让 javascript 工作
- java - H2:多行插入语句出错
- java - 包含方法没有给出正确的输出