javascript - 如何制作一个简单的赞成/反对票系统(vuejs/firebase)?
问题描述
您好,如果问题太明显,请原谅,但我从这个开始并吓坏了。
我尝试让用户可以投票并从另一个用户在同一按钮上发布的项目中删除他的投票,基本上是在寻找类似 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>
有什么前进的想法吗?
解决方案
我已经尝试按照建议去做,但我一直没能做好。
但是,我试图想出替代的方法来做到这一点。
我发现这个很有趣(尽管它可能没有意义,出于某种我不知道的原因)。
1)在创建时向项目添加“upvoted:false”
2)添加了两种方法(一种用于投票,另一种用于downvote)
methods: {
upvoteItem(itemId, upvotes) {
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(() => {
fb.itemsCollection.doc(itemId).update({
upvotes: upvotes + 1,
upvoted: false
})
})
}).catch(err => {
console.log(err)
})
},
downvoteItem(itemId, upvotes) {
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(() => {
fb.itemCollection.doc(itemId).update({
upvotes: upvotes - 1,
upvoted: true
})
})
}).catch(err => {
console.log(err)
})
},
3) 三元运算符点击
<button @click="item.upvoted ? downvoteItem(item.id, item.upvotes) : upvoteItem(item.id, item.upvotes)">{{ item.upvotes }}</button>
但是三元运算符只适用于第一次点击,我无法让第二次点击!
推荐阅读
- python - 将字典列表转换为新字典
- reactjs - 什么时候在 react 中调用 useEffect 挂钩清理函数
- java - 最新稳定版 Elastic Search for Spring boot 2.1.3.RELEASE
- reactjs - React-Redux:如何实际更新依赖于 store 的其他值的 redux store 的状态
- javascript - 我使用 bootstrap4 设计了一个简单的网页,但无论我尝试什么,我都无法使其响应。谁能帮我?
- reactjs - 反应项目的好例子来查看文件夹结构
- sum - 如果有文本,如何对单元格中的数字求和?
- assembly - TASM如何用对应的字母替换一个字符
- node.js - 授权每个请求与从缓存中删除用户会话
- mysql - 如何从 Laravel 7 中的多个模型中获取查询结果?