uniapp 云开发小程序评论与回复功能的简单设计

1.前端视图与云端数据的关系

字段commentList是数组类型,评论内容与昵称为对象类型。
在这里插入图片描述

在这里插入图片描述

在这里插入图片描述
注意 :如果在小程序端调用数据库API,需要把集合的数据权限修改为自定义安全规则 “write” : true 其他用户才能回复评论
在这里插入图片描述

2.实现添加评论的代码

        addComment() {
    
    
        	let data = {
    
    
				avatar:avatarUrl,
				nickName:nickName,
				addTime:new Date(),
				commentList:[{
    
    
					comment:comment,
					nickName: nickName
				}]
			}
			
			// 在数组前面插入数据,使页面实时显示新增加的评论
			this.commentData.unshift(data)
			
			// 把评论保存到云数据库
			wx.cloud.database()
			.collection('videoComment')  //集合名称
			.add({
    
    
				data: data,
				success(res) {
    
    
					console.log('增加成功:', res)
				},
				fail(err) {
    
    
					console.log('增加出错:' , err)
				}
			})
        },

3.实现回复评论的代码

		replyComment() {
    
    	
			const db = wx.cloud.database()
			const com = db.command
			let replyData = {
    
    						
				comment: comment,
				nickName: nickName						
			}
			
			// 回复内容追加到本地数组里面的commentList数组中,使页面实时显示追加的评论
			this.commentData[commentIndex].commentList.push(replyData)
			
			// 回复内容保存到云数据库
			db.collection('videoComment')  //集合名称
			.where({
    
     _id: id })  //评论的id
			.update({
    
    
				data:{
    
    					
					commentList: com.push({
    
      //追加数据到commentList字段
						comment : comment,
						nickName : nickName
					})					
				},
				success(res) {
    
    
					console.log('回复成功:', res)
				},
				fail(err) {
    
    
					console.log('回复出错:' , err)
				}
			})
		},

おすすめ

転載: blog.csdn.net/weixin_38946164/article/details/113498533