這里給大家分享我在網上總結出來的一些知識,希望對大家有所幫助

本篇文章主要總結了微信小程式開發,獲取用戶資訊的整個流程步驟,補充了網上很多碎片化的代碼,本人梳理了思路寫下了這篇文章,
思路
1、在js檔案中,設定userinfo、hasUserinfo、canIUseGetUserProfile資料
2、先判斷本地快取( wx.getStorageSync() )是否含有用戶的資料,如果有就用快取里的資料,沒有就進行第三步
3、在界面添加登錄按鈕,用戶點擊按鈕呼叫wx.getUserProfile()函式來提示用戶授權登錄,授權成功后,把用戶頭像資料和名稱資料保存到快取區里,并且改變全域變數的值
流程圖
自己大概畫了一下大概的流程,但希望對您有幫助!

考慮到一些新手,我將完整代碼發給大家,大家按照代碼對應寫入對應位置即可!
wxml
<view >
<view >
<view catchtap="showBcgImgArea">
<image mode="aspectFill" src="https://www.cnblogs.com/smileZAZ/archive/2022/12/08/{{userinfo.avatarUrl}}"></image>
</view>
<view>
<text >{{userinfo.nickName}}</text>
</view>
</view>
<button wx:if="{{!hasUserInfo && canIUseGetUserProfile}}" open-type="getUserInfo" bindtap="getUserProfile" >
點擊登錄
</button>
</view>
js
注意:avatarUrl:'../../images/ckbg1.png'
這行代碼意思是當沒有獲取到用戶資訊時,頁面展示頭像的路徑,自己要先準備好一張圖片(放在images檔案夾下),并填好頭像路徑!
data: {
//用戶基本資訊(頭像、昵稱)
userinfo: {
avatarUrl:'../../images/ckbg1.png',
nickName:'未授權'
},
//是否已經獲取用戶資訊
hasUserInfo: false,
//是否可以呼叫獲取資訊得函式
canIUseGetUserProfile: false,
},
//第一次獲取用戶資訊
getUserProfile : function(e){
wx.getUserProfile({
desc: '獲取您的微信個人資訊',
success:(res)=>{
this.setData({
userinfo:res.userInfo,
hasUserInfo:true
})
wx.setStorageSync('userinfo', res.userInfo)
},
fail:function(e){
wx.showToast({
title: '你選擇了取消',
icon: "none",
duration: 1500,
mask: true
})
}
})
},
onl oad: function(n) {
this.setData({
canIUseGetUserProfile : true
})
},
onShow: function() {
//獲取用戶的本地快取資料,userinfo資訊是在用戶授權登錄時保存的
var n = wx.getStorageSync("userinfo");
//當本地快取的用戶名稱不為""或者null時,設定userinfo資訊
if(n.nickName != '' && n.nickName != null){
this.setData({
userinfo: n,
hasUserInfo:true,
canIUseGetUserProfile:true
})
// 通過wx.login獲取登錄憑證(code),然后通過code去獲取我們用戶的openid
wx.login({
success:(res)=>{
console.log(res);
},
})
}
//清空快取資訊,測驗使用
// wx.removeStorage({
// key: 'userinfo',
// });
},
在這里有必要講解幾處代碼:
1、當頁面加載完畢時(onLoad函式),我們將canIUseGetUserProfile資料設定ture,代表可以使用使用getUserProfile了,避免頁面沒有加載完畢就去獲取用戶資訊!
2、當頁面即將展示時(onShow函式),呼叫wx.getStorageSync獲取本地快取資料,來控制按鈕的顯示與否
wxss
.banner {
border-radius: 10rpx;
border: none;
box-sizing: content-box;
padding: 20rpx 0;
width: 90%;
height: 370rpx;
margin: 20rpx auto;
background:linear-gradient(109.6deg, rgb(204, 228, 247) 11.2%, rgb(237, 246, 250) 100.2%);
/* background-image:image("../../images/cloudbg.jpg"); */
text-align: center;
}
.topContainer {
width: 100%;
height: 260rpx;
background-size: 100%;
border-radius: 9px;
}
.userinfo-nickname {
color:black;
}
.userLogin{
width: 50%;
box-sizing: none;
font-size: medium;
}
.userinfo-avatar {
width: 150rpx;
height: 150rpx;
margin-bottom: 10rpx;
border-radius: 50%;
}
當快取里沒有記錄用戶資訊時,顯示的頁面會出現登錄按鈕:

點擊按鈕后,彈出授權資訊

點擊允許后,會出現微信頭像和微信名稱

效果展示:

https://blog.csdn.net/calm_programmer/article/details/124207072
如果對您有所幫助,歡迎您點個關注,我會定時更新技術檔案,大家一起討論學習,一起進步,

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/539558.html
標籤:其他
上一篇:自適應且不可洗掉的水印蒙層
