微信小程式:“我的”頁面佈局(一):微信使用者資訊獲取及UI
新專案挖新坑,公司又需要做新的小程式,沒有其他人支援,這次還得前後臺一起做...不懂前端的我又來挖坑了...
先做小程式“我的”頁面,需要注意的有兩個點:
- 考慮到前幾個版本getUserInfo不再彈出授權視窗,所以增加了不可見的button來喚起授權視窗;
- "我的"頁面功能列表雖然現在不多,但是指不定什麼時候就要增加或者修改,所以將該列表做成可配置的,使用了wx:for和navigator。
先上圖,有圖才有真相:

微信小程式--“我的“頁面.jpg
一、 使用者資訊獲取
這一塊我增加了一個隱藏的button, 未獲取到使用者資訊時,顯示為預設頭像和“微信授權”的文字提示,登陸後,頭像變為微信頭像,文字變為微信暱稱。
<button class="login-button head-height" open-type="getUserInfo" bindgetuserinfo="getUserInfo"> 獲取頭像暱稱 </button>
具體ui為判斷沒有授權則顯示預設頭像及提示,並在其上層覆蓋一個透明的button,使用者觸發授權事件。
wxml:
<view class='head head-height'> <block wx:if="{{!hasUserInfo && canIUse}}"> <view class="userinfo"> <image class="userinfo-avatar" src="../../images/icon-mine.png" mode="cover"></image> <text class="userinfo-nickname">微信授權</text> </view> <button class="login-button head-height" open-type="getUserInfo" bindgetuserinfo="getUserInfo"> 獲取頭像暱稱 </button> </block> <block wx:else> <view class="userinfo"> <image bindtap="bindViewTap" class="userinfo-avatar" src="{{userInfo.avatarUrl}}" mode="cover"></image> <text class="userinfo-nickname">{{userInfo.nickName}}</text> </view> </block> </view>
wxss:
.head-height { height: 240rpx; } .head { display:flex; width: 100%; background-color: #15c261; align-items: center; } .login-button { opacity: 0; width: 100%; position: fixed; } .userinfo { display: flex; flex-direction: row; align-items: center; width: 100%; position: fixed; } .userinfo-avatar { width: 150rpx; height: 150rpx; margin: 30rpx; border-radius: 50%; } .userinfo-nickname { color: #333333; font-size: 42rpx; }
js:
在js中需要注意的是,open-type="getUserInfo"需要做老版本相容,老版本通過wx.getUserInfo即可喚起授權頁面,不需要新增button去觸發
//獲取應用例項 const app = getApp(); Page({ /** * 頁面的初始資料 */ data: { userInfo: {}, hasUserInfo: false, canIUse: wx.canIUse('button.open-type.getUserInfo') }, /** * 生命週期函式--監聽頁面載入 */ onLoad: function (options) { var that = this; if (app.globalData.userInfo) { that.setUserInfo(app.globalData.userInfo); } else if (that.data.canIUse) { // 由於 getUserInfo 是網路請求,可能會在 Page.onLoad 之後才返回 // 所以此處加入 callback 以防止這種情況 app.userInfoReadyCallback = res => { that.setUserInfo(res.userInfo); } } else { // 在沒有 open-type=getUserInfo 版本的相容處理 wx.getUserInfo({ success: res => { that.setUserInfo(res.userInfo); } }) } }, getUserInfo: function (e) { this.setUserInfo(e.detail.userInfo); }, setUserInfo: function (userInfo) { if (userInfo != null) { app.globalData.userInfo = userInfo this.setData({ userInfo: userInfo, hasUserInfo: true }) } } }
一、 使用者資訊獲取
詳情見下一篇: 微信小程式:“我的”頁面佈局(二):可配置功能選單列表
簡書:ThinkinLiu 部落格:IT老五

IT老五(it-lao5):關注公眾號,一起源創,一起學習!
相關推薦:
微信小程式:“我的”頁面佈局(一):微信使用者資訊獲取及UI
微信小程式:“我的”頁面佈局(二):可配置功能選單列表