小程序用户登录功能

image.png

设置traceUser属性

 wx.cloud.init({
      env: 'mybili-xrruy',
      traceUser:true,
    })
button绑定两个属性
<button wx:if="{{!isLogin}}" size="mini" open-type="getUserInfo" bindgetuserinfo="getUserInfo">登录</button>
通过云函数可以直接拿到用户的_openId,方便后面的数据库查询添加数据
const cloud = require('wx-server-sdk')
exports.main = (event, context) => {
  // 这里获取到的 openId、 appId 和 unionId 是可信的,注意 unionId 仅在满足 unionId 获取条件时返回
  let { OPENID, APPID, UNIONID } = cloud.getWXContext()

  return {
    OPENID,
    APPID,
    UNIONID,
  }
}
以下就是数据库查询,添加用户信息到云数据库
getUserInfo: function(result){
    // console.log(result);
    this.setData({
      isLogin:true
    })
    let openId = "";
    // 调用云函数获取当前的openId
    wx.cloud.callFunction({
      // 云函数名称
      name: 'getopenid',
      // 传给云函数的参数
      success: function (res) {
        openId = res.result.event.userInfo;
        // console.log(res.result.event.userInfo)
      },
      fail: console.error
    })
    // 获取用户信息列表查询,需要拿到用户的openid,数据库中查询是否存在
    USERDB.where({
      _openid: openId
    }).get()
      .then(res => {
        console.log(res)
        if(res.data.length>0){
          // 如果存在
          this.setData({
            userlist: res.data
          })
          this.onLoad()
          return
        }else {
          // 不存在增加数据
          USERDB.add({
            data: result.detail.userInfo,
            success: res => {
              console.log(res)
              this.setData({
                userlist: result.detail.userInfo
              })
              this.onLoad()
            },
            fail: res => {
              console.log(res)
            }
          })
        }
      })
      .catch(res => {
        // 数据库中不存在则添加数据
        console.log(res)
        // 添加用户信息到数据库,之前先校验是否存在
      })
    
  }

备注:小程序刷新页面用 onLoad()方法

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 下面是主界面和代码。 index.wxml index.js 源码都放在这里了,https://github.co...
    嗯哼65阅读 15,961评论 1 3
  • width: 65%;border: 1px solid #ddd;outline: 1300px solid #...
    邵胜奥阅读 4,894评论 0 1
  • ORA-00001: 违反唯一约束条件 (.) 错误说明:当在唯一索引所对应的列上键入重复值时,会触发此异常。 O...
    我想起个好名字阅读 5,451评论 0 9
  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,145评论 1 32
  • 人生仿佛弹指一挥间, 我们的生命又画上了一道年轮。 岁月让我们学会了世事洞明随遇而安,让我们懂得了把握自己, 坚守...
    淡淡清香_0a7e阅读 159评论 0 0