Sha*_*e G 2 firebase vue.js google-cloud-firestore
我使用 Vue.js 和 Firebase 构建了我能想到的最简单的 CRUD。
当我从表单“创建”数据时,我可以将其发送到数据库,但是当我尝试更新我的本地对象数组时,没有文档 ID,因为这是在我创建新文档时由 firebase 创建的。那么如何在不必从数据库中获取所有数据的情况下检索新文档 id 呢?
必须有一个模式。我唯一能想到的就是再次从数据库中获取“所有”数据。但是有没有更简单的方法呢?
有没有办法将 id 传递回新创建的文档的组件?
这是我的组件,只有必要的位,
<template lang="html">
<div class="crud">
<h1>I am the crud component</h1>
<div v-for="item in peoples" :key="peoples.id" class="peoples">
<h3>name: {{ item.name}} age: {{ item.age}} id: {{ item.id }} <button @click="deletePeople(item.id)">delete</button> </h3>
</div>
<form @submit.prevent="addPerson()">
<div>
<label for="name">Name:</label>
<input type="text" name="name" v-model="name">
</div>
<div>
<label for="age">Age:</label>
<input type="number" name="age" v-model="age">
</div>
<div>
<button>add person to database</button>
</div>
</form>
</div>
</template>
<script>
import db from '@/firebase/init'
export default {
name: 'Crud',
data(){
return {
msg: 'hello all',
peoples: [],
name: null,
age: null
}
},
methods:{
addPerson(){
console.log('addPerson() method running');
console.log('person: ' + this.name);
db.collection('people').add({
name: this.name,
age: this.age
}).then(() => {
db.collection('people').get().then(snapshot => {
this.peoples = []
snapshot.forEach(doc => {
// console.log(doc.data(), doc.id);
let people = doc.data()
people.id = doc.id
this.peoples.push(people)
})
})
// console.log('push to local data');
// this.peoples.push({ name: this.name, age: this.age})
})
},
Run Code Online (Sandbox Code Playgroud)
任何帮助将不胜感激,
谢谢
Run Code Online (Sandbox Code Playgroud)// Add a new document with a generated id. db.collection("cities").add({ name: "Tokyo", country: "Japan" }) .then(function(docRef) { console.log("Document written with ID: ", docRef.id); }) .catch(function(error) { console.error("Error adding document: ", error); });
https://firebase.google.com/docs/firestore/manage-data/add-data
在这里,您可以简单地说this.lastID = docRef.idin ,.then()然后您可以简单地读出带有 ID 的文档lastID。
| 归档时间: |
|
| 查看次数: |
4521 次 |
| 最近记录: |