创建微信小程序空项目
配置结构:
在pages中创建index文件夹并创建JavaScript文件index.js、数据结构的文件index.json、页面结构文件index.wxml和页面样式表文件index.wxss。
视图设计:
如图所示设计头像预览框,昵称预览框,头像和昵称获取按钮,并设计页面的上边栏和下边栏。
功能实现:
视图实现
1. 设置基础调试库版本为2.18.1,兼容getUserProfile()函数获取用户信息。
2. 编写index.wxml文件实现页面结构的设置。
更改app.json文件中的navigationBar属性实现上边栏的设置。
"window": {
"navigationBarTextStyle": "white",
"navigationBarTitleText": "uni-app",
"navigationBarBackgroundColor": "#8B1A1A",
"backgroundColor": "#eeeeee"
}
3. 使用<image>标签实现头像预览框的显示。
<image class="avatar" src="{{avatarUrl}}" mode="aspectFill"></image>
4. 使用<text>标签实现昵称预览框的显示。
<text class="nickname" >{{nickname}}</text>
5. 使用<button>标签设置按钮。
<button bindtap="getUserProfile">获取昵称和头像</button>
6. 使用<view>标签实现下边栏的显示。
<view class="usermotto">
<text class="user-motto" style="color: rgb(255, 255, 255);">{{motto}}</text>
</view>
7. 对应实现wxss设置。
功能界面
1. 编写index.js的data属性。
2. 编写getUserProfile()函数实现获取用户信息功能。
data: {
motto:'YDRJ',
avatarUrl: 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0',
nickname: '请获取昵称'
}
getUserProfile: function() {
if (wx.canIUse('getUserProfile')) {
wx.getUserProfile({
desc: '完善资料',
success: (res) => {
this.setData({
avatarUrl: res.userInfo.avatarUrl,
nickname: res.userInfo.nickName
});
},
fail: (err) => {
wx.showToast({
title: '获取用户信息失败',
icon: 'none'
});
console.error(err);
}
});
} else {
wx.showModal({
title: '提示',
content: '请升级您的微信版本以使用该功能',
showCancel: false
});
}
}
实验结果:
登录过程
获取成功