javascript - Firebase 的更新功能滞后于浏览器上的按钮点击
问题描述
我正在尝试使用 firebase 在 Vue 中创建一个实时投票应用程序来存储投票数。我能够创建数据库并增加投票数,以及将来自数据库的最新投票显示到我的应用程序。但是,当我单击按钮将投票数更新一时,投票仅在浏览器中增加,而不是在 firebase 上。
我使用更新功能错误吗?
...methods:{
upVotePingu() {
let pingu = db.collection('canidates').doc('pingu')
// Atomically increment the population of the city by 50.
pingu.set({
votes: this.pingu.votes++
})
console.log('voted')
}
...mounted(){
db.collection('canidates')
.get()
.then(query => {
query.forEach(doc => {
const dbVote = {
vote: doc.data().votes
}
this.pingu.votes = dbVote.vote
console.log(this.pingu.votes)
})
})
<button @click="upVotePingu">Vote</button>
data() {
return {
pingu: {
votes: 0
}
}
解决方案
您需要执行以下操作:
this.pingu.votes++
pingu.set({
votes: this.pingu.votes
})
另外请注意,要增加字段的值,使用起来更安全FieldValue.increment
,请参阅https://firebase.googleblog.com/2019/03/increment-server-side-cloud-firestore.html和https:// /firebase.google.com/docs/reference/js/firebase.firestore.FieldValue#static-increment