【发布时间】:2020-02-21 04:28:15
【问题描述】:
我正在尝试使用相同的组件来处理我的应用程序的添加和编辑部分。我正在使用 Firebase,所以我正在检查路由参数中是否有 id,如果有,它将呈现为编辑表单,如果没有,则呈现为添加表单。但这不起作用,而且有一些奇怪的行为。
这是ContactForm 组件的代码
<template>
<div>
<div class="card mb-3">
<div class="card-header">{{ editing ? 'Edit' : 'Add' }} Contact</div>
<div class="card-body">
<form @submit.prevent="addContact">
<TextInputGroup
label="Name"
name="name"
placeholder="Enter your name..."
v-model="contact.name"
for="name"
/>
<TextInputGroup
type="email"
label="Email"
name="email"
placeholder="Enter your email..."
v-model="contact.email"
/>
<TextInputGroup
type="phone"
label="Phone"
name="phone"
placeholder="Enter your phone number..."
v-model="contact.phone"
/>
<input type="submit" value="Add Contact" class="btn btn-block btn-light" />
</form>
</div>
</div>
</div>
</template>
<script>
import TextInputGroup from "../layout/TextInputGroup";
import { db } from "../../firebase";
export default {
components: {
TextInputGroup
},
data() {
return {
contact: "",
editing: false,
email: "",
name: "",
phone: ""
};
},
methods: {
addContact() {
const newContact = {
name: this.name,
email: this.email,
phone: this.phone,
createdAt: new Date()
};
db.collection("contacts")
.add(newContact)
.then(docRef => {
console.log("Document written with ID: ", docRef.id);
})
.catch(error => {
console.error("Error adding document: ", error);
});
this.$router.push("/");
},
getContactById() {
db.collection("contacts")
.doc(this.$route.params.id)
.get()
.then(snapshot => {
if (!snapshot.exists) return;
this.contact = snapshot.data();
});
},
updateContact() {
const newContact = {
name: this.contact.name,
email: this.contact.email,
phone: this.contact.phone
};
db.collection("contacts")
.doc(this.$route.params.id)
.update(newContact)
.then(() => {
console.log("Updated document with ID: ");
})
.catch(function(error) {
console.error("Error updating document: ", error);
});
this.$router.push("/");
}
},
mounted() {
if ("id" in this.$route.params) {
this.getContactById();
this.editing = true;
console.log("id");
} else {
console.log("ups");
// this
}
}
};
</script>
【问题讨论】:
-
控制台中有错误信息吗?
-
不...什么都没有
-
如果你只保留创建的钩子呢?我认为它不会改变任何东西,只是尝试任何可以尝试的东西......
-
我不明白,你能解释一下吗?
-
您确定您的联系人集合中有数据并且没有阻止读取数据的安全规则?
标签: javascript firebase vue.js google-cloud-firestore vue-router