设计思路
- 小程序获取用户信息第一步咱们先设计页面样式,而后书写事件js,js须要实现的功能:核心就是点击使用小程序官方api获取用户信息,而后在小程序页面使用{{}}
index.wxml页面
在这个界面采用了简单的逻辑判断语句,还有按钮绑定事件
<view class="container">
<view class="userinfo">
<image wx:if="{{!hasUserInfo && canIUse}}" src="https://gss0.baidu.com/-4o3dSag_xI4khGko9WTAnF6hhy/zhidao/wh%3D600%2C800/sign=775a322c9945d688a357baa294f25126/91ef76c6a7efce1b29b133d5a451f3deb48f6513.jpg"class="userinfo-avatar"></image>
<view wx:if="{{!hasUserInfo && canIUse}}" class="geren">
<text>微信将获取你的我的信息</text>
</view>
<text wx:if="{{!hasUserInfo && canIUse}}" class="userinfo-nickname">亲爱的用户,点击获取昵称进行访问</text>
<button wx:if="{{!hasUserInfo && canIUse}}" open-type="getUserInfo" bindgetuserinfo="getUserInfo" class="huoqu"> 获取头像昵称 </button>
<block wx:else>
<image class="userinfo-avatar" src="https://gss0.baidu.com/-4o3dSag_xI4khGko9WTAnF6hhy/zhidao/wh%3D600%2C800/sign=775a322c9945d688a357baa294f25126/91ef76c6a7efce1b29b133d5a451f3deb48f6513.jpg" mode="cover"></image>
<text class="userinfo-nickname">亲爱的{{userInfo.nickName}},你最近已经进行了受权,能够直接进行访问</text>
<button class="huoqu" bindtap="bindViewTap" > 点击访问 </button>
</block>
</view>
</view>
index.wxss页面
.geren{
color: blueviolet;
}
.userinfo {
display: flex;
flex-direction: column;
align-items: center;
}
.huoqu{
background-color: rgb(130, 231, 218);
}
.userinfo-avatar {
width: 128rpx;
height: 128rpx;
margin: 20rpx;
border-radius: 50%;
}
.userinfo-nickname {
color: #aaa;
width:400rpx;
}
index.js页面
核心:这里 bindViewTap()函数里跳转页面, getUserInfo()获取信息,结合了wxml里按钮里的属性bindgetuserinfo,用户点击该按钮时,会返回获取到的用户信息,回调的detail数据与wx.getUserInfo返回的一致,open-type="getUserInfo"时有效
Page({
data: {
motto: 'Hello World',
userInfo: {},
hasUserInfo: false,
canIUse: wx.canIUse('button.open-type.getUserInfo')
},
//事件处理函数
bindViewTap: function() {
wx.switchTab({
url: '../home/home'
})
},
getUserInfo: function(e) {
console.log(e)
//这是在使用app.js里的
app.globalData.userInfo = e.detail.userInfo
this.setData({
userInfo: e.detail.userInfo,
hasUserInfo: true
})
}
})
app.js页面
这是自定义的小程序界面原生的
App({
onLaunch: function () {
// 登陆
wx.login({
success: res => {
// 发送 res.code 到后台换取 openId, sessionKey, unionId
}
})
// 获取用户信息
wx.getSetting({
success: res => {
if (res.authSetting['scope.userInfo']) {
// 已经受权,能够直接调用 getUserInfo 获取头像昵称,不会弹框
wx.getUserInfo({
success: res => {
// 能够将 res 发送给后台解码出 unionId
this.globalData.userInfo = res.userInfo
// 因为 getUserInfo 是网络请求,可能会在 Page.onLoad 以后才返回
// 因此此处加入 callback 以防止这种状况
if (this.userInfoReadyCallback) {
this.userInfoReadyCallback(res)
}
}
})
}
}
})
},
globalData: {
userInfo: null
}
})
效果展现
