引言
微信小程序為了優化用戶體驗,取消了在進入小程序時立馬出現授權窗口。需要用戶主動點擊按鈕,觸發授權窗口。
那么,在我實踐過程中,出現了以下問題。
1. 無法彈出授權窗口 2. 希望在用戶已經授權的情況下,不顯示按鈕1. 具體實現
app.js的onLaunch()函數中,添加獲取用戶個人信息的代碼段。實現在用戶已經授權的情況(例如第二次打開小程序時)下,自動獲取用戶個人信息,而不需要用戶的授權。
// 獲取用戶信息wx.getSetting({ success: res => { if (res.authSetting['scope.userInfo']) { console.log("app: " + "用戶已經授權") // 已經授權,可以直接調用 getUserInfo 獲取頭像昵稱,不會彈框 wx.getUserInfo({ success: res => { // 可以將 res 發送給后臺解碼出 unionId this.globalData.userInfo = res.userInfo console.log(this.globalData.userInfo) this.globalData.hasUserInfo = true // 由于 getUserInfo 是網絡請求,可能會在 Page.onLoad 之后才返回 // 所以此處加入 callback 以防止這種情況 if (this.userInfoReadyCallback) { this.userInfoReadyCallback(res) } }, fail: (res) => { console.log("app: " + "獲取用戶信息失敗") } }) }else { console.log("app: " + "用戶暫時未授權") } }})me.wxml中添加授權按鈕(具體的頁面根據大家的實際情況)。這里的button組件必須按照如下的形式。
<button open-type="getUserInfo" bindgetuserinfo="你自己定義函數"></button>
<block wx:if="{{!hasUserInfo}}"> <image src='../../images/icon/wechat.png'></image> <button open-type="getUserInfo" bindgetuserinfo="getUserInfo">微信授權登錄</button></block>效果這樣,具體的樣式根據大家的喜好更改

me.js中添加如下變量和方法,在用戶之前沒有授權的情況下,需要用戶主動點擊按鈕。
data: { userInfo: null, hasUserInfo: false},getUserInfo: function(e) { console.log("me: " + "用戶點擊授權") if(e.detail.userInfo){ this.setData({ userInfo: e.detail.userInfo, hasUserInfo: true }) app.data.userInfo = this.userInfo app.data.hasUserInfo = true }}2. 無法彈出授權窗口

這里一定要注意
授權窗口只會在用戶第一次授權時出現,也就是,只會出現一次!!
在微信小程序開發工具里,需要我們清除所有緩存
新聞熱點
疑難解答