文章详情页面-点赞+浏览次数实现
# 文章详情页面-点赞+浏览次数实现
# 一、浏览次数操作
请求文章详情的云函数返回前端之前进行+1操作
// 每次请求进行+1操作
await db.collection('article').update({
browse_count:dbCmd.inc(1)
})
# 二、文章点赞UI处理
使用计算属性进行Ui显示
isCompliments () {
try {
return this.userInfo && this.userInfo.thumbs_up_article_ids.includes(this.articleData._id)
} catch (e) {
return false
}
}
# 三、云函数定义
'use strict';
const db = uniCloud.database()
const dbCmd = db.command // 使用操作符
exports.main = async (event, context) => {
const { articleId, userId } = event;
const userList = await db.collection('user').doc(userId).get();
const thumbs_up_article_ids = userList.data[0].thumbs_up_article_ids
let tempArr = null;
let returnMsg = '';
let thumbsNumber = null;
//todo 判断当前用户是否有点赞操作
if (thumbs_up_article_ids.includes(articleId)) {
tempArr = dbCmd.pull(articleId)
thumbsNumber = -1
returnMsg = '您取消了点赞'
} else {
tempArr = dbCmd.addToSet(articleId)
thumbsNumber = 1
returnMsg = '点赞成功'
}
// 处理用户字段
await await db.collection('user').doc(userId).update({
thumbs_up_article_ids: tempArr
})
// 处理文章数量字段
await await db.collection('article').doc(articleId).update({
thumbs_up_count: dbCmd.inc(thumbsNumber)
})
//返回数据给客户端
return {
code: 0,
data: {
msg: returnMsg
}
}
};
# 四、前端处理用户保存信息
// 用户检测
await this.checkedIsLogin()
const { msg } = await this.$http.update_compliments({ articleId: this.articleData._id, userId: this.userInfo._id })
msg && uni.showToast({
title: msg,
})
// 修改用户信息
let thumbsArr = [...this.userInfo.thumbs_up_article_ids]
if (thumbsArr.includes(this.articleData._id)) {
this.articleData.thumbs_up_count -= 1
thumbsArr = thumbsArr.filter(item => item != this.articleData._id)
} else {
this.articleData.thumbs_up_count += 1
thumbsArr.push(this.articleData._id)
}
this.updateUserInfo({ ...this.userInfo, thumbs_up_article_ids: thumbsArr })