大三课程设计的记录
实现的页面效果
分析表
- message表用来记录好友请求,系统消息等
- 分析表message需要的字段
- addlist:发送好友申请用户的openid,数组
- writeId:接收好友请求的用户
比如上面的图,我作为用户登录后,申请添加“FHIGH”为好友,那我的openid就会添加到addlist字段数组里,而“FHIGH”的openid就是writeId字段的值
实现
- 添加好友按钮,绑定添加好友事件
isFirend :用来判断是否是好有,是的话显示“已是好友”,不是则显示“添加好友”
- 添加好友事件
- 判断用户是否登录,登录状态才可发起好友申请,知道谁发的好友申请
我把登录后的消息写在了全局下,你们可以根据自己的登录逻辑判断是否登录
- 用户登录后,查询message数据库有没有userId的消息记录,没有就添加;有userId的消息记录的话再查询用户有没有申请过,有的话给申请过的提示消息,没有就更新
addFriend(){
if(app.userInfo._id){
// 把向这条词圈用户发送好友请求的 用户放到一个数组里
// 先查找
db.collection('message').where({
writeId:this.properties.userContent._openid
}).get().then(res=>{
if(res.data.length){
if(res.data[0].addlist.includes(app.userInfo._openid)){
wx.showToast({
title: '已申请过!',
})
}
else{
// console.log("///",app.userInfo._openid)
wx.cloud.callFunction({
name:'update',
data:{
writeId:this.properties.userContent._openid,
addid:app.userInfo._openid
}
}).then(res=>{
// console.log("结果:",res)
wx.showToast({
title: '申请成功~',
})
})
}
}else(
db.collection('message').add({
data:{
writeId:this.properties.userContent._openid,
addlist:[app.userInfo._openid]
}
}).then((res)=>{
wx.showToast({
title: '申请成功',
})
})
)
})
}else{
wx.showToast({
title: '请先登录',
duration:2000,
success:res=>{
setTimeout(()=>{
wx.switchTab({
url: '/pages/my/my',
})
},2000)
}
})
}
},
云函数
- writeId的用户登录后就要接收到好友申请,进行实时监听,发送好友申请的时候,那个用户在登录状态,这时候在他没有刷新的情况下也能监听
消息监听的方法
getMessage(){
db.collection('message').where({
writeId:app.userInfo._openid//监听writeId字段
}).watch({
onChange:function(snapshot){
if(snapshot.docChanges.length){//有长度说明有消息,给用户提示
let list=snapshot.docChanges[0].doc.addlist
if(list.length){
wx.showTabBarRedDot({
index:2
})
app.userMessage=list//list数据要在消息页面下用,写到全局下
}else{
wx.hideTabBarRedDot({
index: 2,
})
app.userMessage=[]
}
}
},
onError:function(err){
console.error('the watch closed because of error', err)
}
})
在登录后调用
注意数据库的权限
- 写removeList组件来渲染好友申请
messageId为发送请求用户的openid,userMessage为请求用户的信息,根据该messageId去数据库找该用户的信息,写在生命周期里
点击头像携带数据跳转到详情页面
<navigator url="{
{'/pages/detail/detail?openid='+userMessage._openid+'&&photo='+userMessage.userPhoto+'&&name='+userMessage.nickName }}" open-type="navigate">
<image src="{
{userMessage.userPhoto}}"></image>
</navigator>
删除的方法:用户点击确认的话,去数据库message表查找收到消息用户的那条记录,用filter() 方法过滤掉addlist数组里面这个要添加好友的openid,更新数据库,更新成功后在子组件触发自定义函数(通过子组件影响父组件,子父通讯)并把更新后的addlist传过去,在父组件中更新渲染子组件的数据
filter() 方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。
父子通讯通过自定义属性
子父通讯通过自定义函数
- 在消息页面,读取全局的app.userMessage,渲染,需要在onShow不断监听页面,同意也是需要在登录状态下接收消息
实现添加好友功能
思路:点击验证弹出模态框,用户点击确认后,把这条消息删除(和左滑点击删除一样)同时让发送好友申请的用户和当前应用的用户产生好友关系(给用户加一个frendList的字段),