微信小程序云开发5

本文详细介绍了在微信小程序中实现添加好友功能的完整流程,包括用户登录状态判断、数据库操作、云函数更新以及实时监听好友请求的推送。同时,展示了在Message页面展示好友列表和删除好友的操作,以及获取和展示用户位置信息的方法。涉及到的技术点包括数据库查询、云函数调用、地图API和组件交互。
摘要由CSDN通过智能技术生成
  1. 添加好友功能实现

    1. 添加好友,如果未登录,需要跳转到我的页面登陆,如果已经登陆,需要进行修改和更新数据库操作,这时修改了update云函数

    detail.wxml

      <button wx:if="{{isFriend  }}">已是好友</button>
      <button wx:else bindtap="handleAddFriend">添加好友</button>
    

    detail.js

    handleAddFriend(){
        if(app.userInfo._id){
          db.collection('message').where({
            userId: this.data.detail._id
          }).get().then((res)=>{
            if(res.data.length){ //更新操作
              if(res.data[0].list.includes(app.userInfo._id)){
                wx.showToast({
                  title: '已申请过!',
                })
              }else{
                wx.cloud.callFunction({
                  name:'update',
                  data:{
                    collection:'message',
                    where:{
                      userId:this.data.detail._id
                    },
                    data:`{list:_.unshift('${app.userInfo._id}')}`
                  }
                }).then(()=>{
                  wx.showToast({
                    title: '申请成功~',
                  })
                });
              }
            }else{ // 添加
              db.collection('message').add({
                data:{
                  userId:this.data.detail._id,
                  list:[app.userInfo._id]
                }
              }).then((res)=>{
                wx.showToast({
                  title: '申请成功',
                })
              })
            }
          
          })
    
        }
        else {
          wx.showToast({
            title: '请先登陆',
            duration:2000,
            icon:'none',
            success:()=>{
              setTimeout(()=>{
                //  这里不能使用navigateTo,因为是tabber跳转,需要使用switchTap
                // 这里添加好友如果没有登陆,就跳转到我的登陆页面
                wx.switchTab({
                  url: '/pages/user/user',
                })
              },2000);
            }
          })
        }
      }
    

    update.js

    // 云函数入口文件
    const cloud = require('wx-server-sdk')
    
    cloud.init({
      env: cloud.DYNAMIC_CURRENT_ENV
    })
    const db = cloud.database()
    //获取db command库的函数
    const _ = db.command
    
    // 云函数入口函数
    exports.main = async (event, context) => {
      try {
    
        // 前台转化为字符串送到后台,然后后台解析字符串运算后传回前台
        if(typeof event.data == 'string'){
          // eval把字符串转化为json
          event.data = eval('('+event.data+')');
        }
         if(event.doc){
                  return await db.collection(event.collection)
                  .doc(event.doc)
                  .update({
                    data: {
                      // 扩展运算符
                      ...event.data
                    },
                  })
                }else {
                  return await db.collection(event.collection)
                  // 加好友的更新操作
                  .where({...event.where})
                  .update({
                    data: {
                      // 扩展运算符
                      ...event.data
                    },
                  })
                }
              } catch(e) {
                console.error(e)
              }
            }
    

    添加好友之实时监听提示,如果有好友发送了请求,则在tabber栏上显示小红点

    getMessage(){
      //  监听,实时数据推送
      db.collection('message').where({
        userId : app.userInfo._id
      }).watch({
        onChange: function (snapshot) {
          if ( snapshot.docChanges.length ){
            let list = snapshot.docChanges[0].doc.list;
            if( list.length ){
              wx.showTabBarRedDot({
                index: 2
              });
              // 传数据给全局变量
              app.userMessage = list;
            }
            else{
              wx.hideTabBarRedDot({
                index: 2
              })
              app.userMessage = [];
            }
          }
        },
        onError: function (err) {
          console.error('the watch closed because of error', err)
        }
      });
    },
    

    app.js 设置全局变量,userMessage

    // 添加好友信息
    this.userMessage=[]
    
    1. Message页面编写,以及添加好友,删除好友操作

      message.wxml

      <!--miniprogram/pages/message/message.wxml-->
      <view class="message" wx:if="{{logged}}">
        <view  wx:if="{{!userMessage.length}}">
          <text  class="message-text">暂无消息:</text>
        </view>
        <view wx:else>
          <text class="message-text">消息列表:</text>
          <!-- item为openid列表 -->
          <!-- <view wx:for="{{userMessage}}" wx:key="{{index}}">{{item}}</view> -->
          <remove-list wx:for="{{userMessage}}" wx:key="{{index}}" messageId = "{{ item }}" bindmyevent="onMyEvent" />
        </view>
      </view>
      
      

      Message.js

      // miniprogram/pages/message/message.js
      
      //创建一个app对象,可以用app对象获取app.js中的userInfo
      const app = getApp()
      Page({
      
        /**
         * 页面的初始数据
         */
        data: {
          userMessage:[],
          logged:false,
        },
      
      
        /**
         * 生命周期函数--监听页面显示
         */
        onShow: function () {
          if (app.userInfo._id){
            this.setData({
              logged:true,
              userMessage:app.userMessage
            });
          }else{
            wx.showToast({
              title: '请先登陆',
              duration:2000,
              icon:'none',
              success:()=>{
                setTimeout(()=>{
                  //  这里不能使用navigateTo,因为是tabber跳转,需要使用switchTap
                  // 这里添加好友如果没有登陆,就跳转到我的登陆页面
                  wx.switchTab({
                    url: '/pages/user/user',
                  })
                },2000);
              }
            })
      
          }
        },
      
        onMyEvent(ev){
          // 列表清空后重新赋值
          this.setData({
            userMessage : []
          },()=>{
              this.setData({
                muserMessage: ev.detail
              });
          });
        }
      })
      

      message页面使用了removeList组件

      removeList.wxml

      <!--components/removeList/removeList.wxml-->
      <!-- 删除组件 -->
      <movable-area class="area">
          <movable-view bindtap="handleAddFriend" direction="horizontal" class="view">{{ userMessage.nickName }}</movable-view>
          <navigator url="{{ '/pages/detail/detail?userId=' + userMessage._id }}" open-type="navigate">
            <!--  点击头像跳到详情页 -->
            <image src="{{ userMessage.userPhoto }}" />
          </navigator>
          <view class="delete" bindtap="handleDelMessage">删除</view>
      </movable-area>
      
      

      removeList.js

      // components/removeList/removeList.js
      
      const app = getApp()
      const db = wx.cloud.database()
      const _ = db.command
      
      Component({
        /**
         * 组件的属性列表
         */
        properties: {
          messageId:String
        },
      
        /**
         * 组件的初始数据
         */
        data: {
          userMessage : {}
        },
      
        /**
         * 组件的方法列表
         */
        methods: {
          handleDelMessage(){
            wx.showModal({
              title: '提示信息',
              content: '删除消息',
              confirmText: '删除',
              success:(res)=>{
                if (res.confirm) {
                  this.removeMessage();
                } else if (res.cancel) {
                  console.log('用户点击取消')
                }
              }
            })
          },
          handleAddFriend(){
            wx.showModal({
              title: '提示信息',
              content: '申请好友',
              confirmText: '同意',
              success: (res) => {
                if (res.confirm) {
                  // 数据库中添加friendList字段
                  db.collection('users').doc(app.userInfo._id).update({
                    data : {
                      friendList : _.unshift(this.data.messageId)
                    }
                  }).then((res)=>{}); 
                  // 另一个好友添加字段,改变另一个账号需要用到云函数
                  wx.cloud.callFunction({
                    name : 'update',
                    data : {
                      collection : 'users',
                      doc : this.data.messageId,
                      data: `{friendList: _.unshift('${app.userInfo._id}')}`
                    }
                  }).then((res)=>{});
                  // 同意后移除显示
                  this.removeMessage();
                } else if (res.cancel) {
                  console.log('用户点击取消')
                }
              }
            })
          },
          removeMessage(){
            db.collection('message').where({
              userId: app.userInfo._id
            }).get().then((res) => {
              console.log(res.data[0].list);
              let list = res.data[0].list;
              list = list.filter((val, i) => {
                return val != this.data.messageId
              });
              wx.cloud.callFunction({
                name: 'update',
                data: {
                  collection: 'message',
                  where: {
                    userId: app.userInfo._id
                  },
                  data: {
                    list
                  }
                }
              }).then((res) => {
                // 删除后取消好友页面
                this.triggerEvent('myevent', list);
              });
            });
          }
        },
        lifetimes: {
          attached: function () {
            db.collection('users').doc(this.data.messageId).field({
              userPhoto : true,
              nickName : true
            }).get().then((res)=>{
                
              this.setData({
                userMessage : res.data
              });
      
            });
           
          }
        }
      })
      
      
      1. 获取自己的位置以及好友的位置

        near.wxml

        <!--miniprogram/pages/near/near.wxml-->
        <!-- <search /> -->
        <view class="map">
          <map id="map" longitude="{{ longitude }}" latitude="{{ latitude }}" scale="14" show-location markers="{{markers}}" bindmarkertap="markertap"></map>
        </view>
        

        near.js

        // miniprogram/pages/near/near.js
        
        const app = getApp()
        const db = wx.cloud.database()
        const _ = db.command
        
        
        Page({
        
          /**
           * 页面的初始数据
           */
          data: {
            longitude : '',
            latitude : '',
            markers : [],
            markers_id: ''
          },
          getLocation(){
            // 获取当前位置
            wx.getLocation({
              type: 'gcj02',
              success: (res)=> {
                const latitude = res.latitude
                const longitude = res.longitude
                this.setData({
                  longitude,
                  latitude
                });
                this.getNearUsers();
              }
            })
          },
          getNearUsers(){
            db.collection('users').where({
              location: _.geoNear({
                geometry: db.Geo.Point(this.data.longitude, this.data.latitude),
                // 附近的人范围
                minDistance: 0,
                maxDistance: 5000
              }),
              isLocation : true
            }).field({
              longitude : true,
              latitude : true,
              userPhoto : true
            }).get().then((res)=>{
              //  console.log( res.data );
               let data = res.data;
               let result = [];
              //  是否开启位置
               if(data.length){
                 for(let i=0;i<data.length;i++){
                   if (data[i].userPhoto.includes('cloud://') ) {
                     wx.cloud.getTempFileURL({
                       fileList: [ data[i].userPhoto ],
                       success: res => {
                         result.push({
                           iconPath: res.fileList[0].tempFileURL,
                           id: data[i]._id,
                           latitude: data[i].latitude,
                           longitude: data[i].longitude,
                           width: 30,
                           height: 30
                         });
                         this.setData({
                           markers: result,
                           markers_id:result.id
                         });
                       }
                     })
                   }
                   else {
                     result.push({
                       iconPath: data[i].userPhoto,
                       id: data[i]._id,
                       latitude: data[i].latitude,
                       longitude: data[i].longitude,
                       width: 30,
                       height: 30,
                     });
                     
                   }
                 }
                 console.log(result);
                 console.log(result.id);
                //   因为是异步的,所以要再次渲染一下
                 this.setData({
                   markers: result,
                   markers_id:result.id
                 });
               }
            });
          },
          markertap(ev){
            //跳转到详情页
            // wx.navigateTo({
            //   url: '../detail/detail?userId=' + ev.markerId
            // })
            console.log(markers_id);
          }
        })
        
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值