其他分享
首页 > 其他分享> > <button open-type=“getUserInfo“> 目前已经不支持,快乐的用wx.getUserProfile()吧

<button open-type=“getUserInfo“> 目前已经不支持,快乐的用wx.getUserProfile()吧

作者:互联网

官方地址:
https://developers.weixin.qq.com/miniprogram/dev/api/open-api/user-info/wx.getUserProfile.html

wx.getUserProfile获取用户信息。页面产生点击事件(例如 button 上 bindtap 的回调中)后才可调用,每次请求都会弹出授权窗口,用户同意后返回 userInfo。该接口用于替换 wx.getUserInfo,每次都弹兄弟们记得加if判断

  // 页面的初始数据
  data: {
    isShowUserName: false,
    userInfo: null,
  },
  //获取用户信息
  getUserProfile() {
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
      success: (res) => {
        console.log("获取用户信息成功", res)
        let user = res.userInfo
        this.setData({
          isShowUserName: true,
          userInfo: user,
        })
        user.openid = app.globalData.openid;
        app._saveUserInfo(user);
      },
      fail: res => {
        console.log("获取用户信息失败", res)
      }
    })
  },
  
  //退出登录
  tuichu() {
    wx.setStorageSync('user', null)
    this.setData({
      userInfo: null,
      isShowUserName: false
    })
  },
<view wx:if="{{!isShowUserName}}" class="btn-login">
	<button type="primary" bindtap="getUserProfile">授权登陆</button>
</view>

也可以使用页面全局变量判断登录状态

组件内写法

  data:{
    userInfo:null,
    hasUserInfo:false,
  },
  methods: {
    onChallengeFriend: throttle(async function(e) {
      if(!this.data.hasUserInfo) {
        wx.getUserProfile({
          desc: '用于完善会员资料', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
          success: (res) => {
            this.setData({
              userInfo: res.userInfo,
              hasUserInfo:true,
            })
            userModel.updateInfo(this.data.userInfo) // 更新用户信息
            this.triggerEvent('onChallengeFriend')
          },
          fail:()=> {
            this.selectComponent('#authFailMessage').show()
          }
        })
      }
      if(this.data.hasUserInfo) {
        userModel.updateInfo(this.data.userInfo) // 更新用户信息
        this.triggerEvent('onChallengeFriend')
      }
    }, 1000),

标签:user,getUserInfo,res,button,data,userInfo,open,getUserProfile,wx
来源: https://blog.csdn.net/m0_45953836/article/details/121442381