【发布时间】:2019-10-30 06:12:18
【问题描述】:
你好,如果问题太明显,请原谅,但我从这个开始,吓坏了。
我尝试让用户可以投票并从另一个用户在同一按钮上发布的项目中删除他的投票,基本上是在寻找类似 twitter 的最爱的功能,我已经设法让它投票,但我不是成功删除投票。
赞成票的代码部分(至少对我有用)如下:
import { mapState } from 'vuex'
const fb = require('../firebaseConfig.js')
export default {
computed: {
...mapState(['userProfile', 'currentUser', 'items'])
},
methods: {
upvoteItem(itemId, itemUpvotes) {
let docId = `${this.currentUser.uid}_${itemId}`
fb.upvotesCollection.doc(docId).get().then(doc => {
if (doc.exists) { return }
fb.upvotesCollection.doc(docId).set({
itemId: itemId,
userId: this.currentUser.uid
}).then(() => {
// actualizar item upvotes
fb.itemsCollection.doc(itemId).update({
upvotes: itemUpvotes + 1,
})
})
}).catch(err => {
console.log(err)
})
},
}
}
然后是 html 进行投票(并显示计数器):
<button @click="upvoteItem(item.id, item.upvotes)">{{ item.upvotes }}</button>
有什么前进的想法吗?
【问题讨论】:
-
您很可能应该在代码中使用事务,请参阅firebase.google.com/docs/firestore/manage-data/…。在检查了
upvotes的值大于 1 之后,你为什么不做.update({ upvotes: itemUpvotes - 1, })的投票?? -
使用事务是正确的方法。
标签: javascript firebase vue.js google-cloud-firestore