获取用户信息并且缓存信息

最近微信小程序对于审核小程序提出了带有wx.login、wx.getUserInfo接口的调整,并提出了一个新的接口供开发者调用

点击前往官网查看更多详细信息


wxml:

<view class="login">
    <!-- 当已经授权登录的时候 -->
    <view class="left" wx:if="{{loginResult}}">
        <image src="{{userTouxiang}}" mode="widthFix"></image>
        <view class="text">
            <text class="name">{{userName}}</text>
            <text class="tell">{{userPhone}}</text>
        </view>
    </view>
    <!-- 未登录 -->
    <view class="left" wx:else>
        <image src="../../images/unLogin.png" mode="widthFix"></image>
        <text class="btn" catchtap="getUserProfile">立即登录</text>
    </view>
    <text class="iconfont icon-arrow1"></text>
</view>

wxss:

page {
  background-color: #f7f7f7;
}
.login {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #fff;
  padding: 18rpx 20rpx;
  margin: 18rpx 0;
}
.login .left {
  display: flex;
  align-items: center;
}
.login .left image {
  width: 120rpx;
  height: 120rpx;
  border-radius: 120rpx;
  margin-right: 20rpx;
}
.login .left .name,
.login .left .tell {
  display: block;
}
.login .left .name {
  font-size: 32rpx;
  margin-bottom: 12rpx;
}
.login .left .tell {
  color: #888;
  font-size: 26rpx;
}
.login .left .btn {
  background-color: #1D8FE1;
  color: #fff;
  font-size: 26rpx;
  padding: 10rpx 15rpx;
  border-radius: 6rpx;
}
.login .iconfont {
  color: #1D8FE1;
}

js

onLoad: function (options) {
  var that = this;

  this.getUserProfile()

  // 判断是否已经登录
  // 读取缓存
  console.log(wx.getStorageSync('userName'))
  if(wx.getStorageSync('loginResult')){
    this.setData({
      userName: wx.getStorageSync('userName'),
      userTouxiang: wx.getStorageSync('userTouxiang'),
      userPhone: wx.getStorageSync('userPhone'),
      loginResult: wx.getStorageSync('loginResult')
    })
  }
},
getUserProfile() {
  // 推荐使用wx.getUserProfile获取用户信息,开发者每次通过该接口获取用户个人信息均需用户确认
  // 开发者妥善保管用户快速填写的头像昵称,避免重复弹窗
  wx.getUserProfile({
    desc: '获取用户的昵称、头像和手机号', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
    success: (res) => {
      this.setData({
        userName: res.userInfo.nickName,
        userTouxiang:res.userInfo.avatarUrl,
        userPhone:"1508994256", //获取手机号需要后台处理
        loginResult: true
      })

      // 存入缓存
      wx.setStorageSync("userName",res.userInfo.nickName)
      wx.setStorageSync("userTouxiang",res.userInfo.avatarUrl)
      wx.setStorageSync("userPhone", "1508994256")
      wx.setStorageSync("loginResult", true)
    }
  })
},
posted @ 2021-07-16 23:41  星河几重  阅读(227)  评论(0编辑  收藏  举报