[英]Submit form only if value of input change
I have a form with some input fields and I am using some firebase methods to update those fields.我有一个包含一些输入字段的表单,我正在使用一些 firebase 方法来更新这些字段。 But everytime when clicking the submit button the entire form is submitting.
但是每次单击提交按钮时,整个表单都在提交。 How can I check if any if the fields value changed.
如果字段值发生变化,我如何检查是否有任何变化。 For an example if display name remains same then the updateProfile method will not run on submit.
例如,如果显示名称保持不变,则 updateProfile 方法将不会在提交时运行。 Please find the code below.
请在下面找到代码。 onUpdateProfile is the form submit method.
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
};
},
}
To only update the user document if there are any changes, you'll need to compare the values inside the document with the values from the form.要仅在有任何更改时更新用户文档,您需要将文档中的值与表单中的值进行比较。 Something like this:
像这样的东西:
//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)
}
The changes I made here:我在这里所做的更改:
updates
object with only the values that have changed.updates
对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.