调用wx.getUserProfile()
<view wx:if="{{!userInfo}}"> <button bindtap="login">获取用户头像昵称</button> </view> <view wx:else class="userinfo"> <image class="userinfo-avatar" src="{{userInfo.avatarUrl}}"></image> <text>{{userInfo.nickName}}</text> <button bindtap="logout">退出登录</button> </view>
.userinfo { display: flex; flex-direction: column; align-items: center; } .userinfo-avatar { width: 200rpx; height: 200rpx; border-radius: 50%; }
Page({ data: { userInfo:'' }, login(){ wx.getUserProfile({ desc: '用于记录用户信息', success:res =>{ console.log(res) this.setData({ userInfo: res.userInfo }) }, fail:res =>{ console.log("授权失败!",res) } }) }, logout(){ this.setData({ userInfo:'' }) } })
wx.setStorageSync()
Page({ data: { userInfo:'' }, onl oad() { //取缓存 let userinfo = wx.getStorageSync('userInfo') this.setData({ userInfo:userinfo }) }, login(){ wx.getUserProfile({ desc: '用于记录用户信息', success:res =>{ console.log(res) //用户信息缓存到本地 wx.setStorageSync('userInfo', res.userInfo) this.setData({ userInfo: res.userInfo }) }, fail:res =>{ console.log("授权失败!",res) } }) }, logout(){ this.setData({ userInfo:'' }) wx.setStorageSync('userInfo', '') } })