javascript - 仅在输入值更改时提交表单
问题描述
我有一个带有一些输入字段的表单,我正在使用一些 firebase 方法来更新这些字段。但是每次单击提交按钮时,整个表单都在提交。如果字段值更改,我如何检查是否有。例如,如果显示名称保持不变,那么 updateProfile 方法将不会在提交时运行。请在下面找到代码。onUpdateProfile 是表单提交方法。
{
methods: {
onUpdateProfile() {
firebase.auth().onAuthStateChanged(user => {
if (user) {
//Getting Current User
//Updating User name on submit
let user = firebase.auth().currentUser;
user
.updateProfile({
displayName: this.profile.name
})
.then(() => {
this.formSuccess = "Name changed successfully.";
setTimeout(() => {
$(".form-success").fadeOut("slow");
}, 2500);
})
.catch(error => {});
//Updating User other details on submit
const db = firebase.firestore().collection("profiles");
db.get()
.then(doc => {
if (doc.exists) {
//If user data exists it will update
db.doc(user.uid)
.update({
phonenumber: this.profile.phonenumber,
fulladdress: this.profile.fullAddress,
zipcode: this.profile.zipcode
})
.then(() => {
this.formSuccess = "Profile Updated successfully.";
setTimeout(() => {
$(".form-success").fadeOut("slow");
}, 2500);
})
.catch(error => {});
} else {
//If user data not exists it will create new collection and add the new user records
db.doc(user.uid)
.set({
phonenumber: this.profile.phonenumber,
fulladdress: this.profile.fullAddress,
zipcode: this.profile.zipcode
})
.then(() => {
this.formSuccess = "Profile Updated successfully.";
setTimeout(() => {
$(".form-success").fadeOut("slow");
}, 2500);
})
.catch(error => {});
}
})
.catch(error => {});
} else {}
});
},
},
data() {
return {
profile: {
name: "",
email: "",
phonenumber: "",
fullAddress: "",
zipcode: "",
},
formSuccess: null
};
},
}
解决方案
要仅在有任何更改时更新用户文档,您需要将文档中的值与表单中的值进行比较。像这样的东西:
//Updating User other details on submit
const db = firebase.firestore().collection("profiles");
db.doc(user.uid).get()
.then(doc => {
if (doc.exists) {
var updates = {};
if (doc.data().phonenumber != this.profile.phonenumber) updates["phonenumer"] = this.profile.phonenumber;
if (doc.data().fulladdress != this.profile.fullAddress) updates["fulladdress"] = this.profile.fullAddress;
if (doc.data().zipcode != this.profile.zipcode) updates["zipcode"] = this.profile.zipcode;
if (Object.keys(updates).length > 0) {
db.doc(user.uid).update(updates)
}
我在这里所做的更改:
- 您的代码加载了所有用户配置文件,而上面只加载了当前用户的配置文件。
updates
仅使用已更改的值构建一个对象。- 仅在有任何更改时才更新数据库。
推荐阅读
- java - BufferedReader 超时
- compiler-errors - 以下 Fortran 代码有什么问题?(gfortran) (1) 处的 DTIO 虚拟参数必须是 ASSUMED SHAPE ARRAY
- java - 如何使用 Java 中的 YouTube API 检查 YouTube 视频是否存在?
- python - 如何在numpy中执行重复填充?
- html - 有没有办法用键盘快捷键砍掉一个 html 标签?
- python - 如何将 my_dict 传递给重定向,例如 redirect('home',my_dict)
- c# - 如何在更新条带连接帐户时使用公司参数
- c - 结构中“(”标记之前的 C 错误预期标识符
- python - Spyder 控制台不显示输出
- javascript - 如何使父组件成为其子组件的标签?