實(shí)現(xiàn)步驟
1. 通過定義button按鈕點(diǎn)擊事件,點(diǎn)擊登錄后觸發(fā)事件
2. 通過wx.getUserProfile API調(diào)用用戶信息
3. 獲取成功就將數(shù)據(jù)存儲(chǔ)到本地存儲(chǔ)中,使用wx.setStorageSync('user',?user)
4. 存儲(chǔ)完獲取本地?cái)?shù)據(jù)wx.getStorageSync('user')文章來源:http://www.zghlxwxcb.cn/news/detail-751538.html
5. 頁面渲染數(shù)據(jù) 實(shí)現(xiàn)登錄文章來源地址http://www.zghlxwxcb.cn/news/detail-751538.html
wxml頁面
<!--登錄-->
<button wx:if="{{!userInfo}}" bindtap="login">登錄</button>
<view wx:else class="root">
<image class="touxiang" src="{{userInfo.avatarUrl}}"></image>
<text class="nicheng">{{userInfo.nickName}}</text>
</view>
<!--退出登錄-->
<view wx:if="{{userInfo}}">
<button bindtap="nologin" >
<text>退出登錄</text>
</button>
</view>
js頁面?
Page({
/**
* 頁面的初始數(shù)據(jù)
*/
data: {
// 用戶信息
userInfo:'',
},
/**
* 生命周期函數(shù)--監(jiān)聽頁面加載
*/
onLoad(options) {
})
// 用于獲取緩存,進(jìn)入小程序時(shí)調(diào)用
let user=wx.getStorageSync('user')
this.setData({
userInfo:user
})
},
// 登錄
login(){
console.log('點(diǎn)擊事件執(zhí)行了')
wx.getUserProfile({
desc: '必須授權(quán)才能使用',
success:res=>{
let user=res.userInfo
wx.setStorageSync('user', user)
console.log('成功',res)
this.setData({
userInfo:user
})
wx.navigateBack({
})
},
fall:res=>{
console.log('失敗',res)
}
})
},
// 退出登錄
nologin(){
this.setData({
userInfo:''
})
wx.setStorageSync('user', null)
}
})
wxss頁面
.touxiang {
width: 150rpx;
height: 150rpx;
border-radius: 50%;
margin-top: 20rpx;
margin-bottom: 10rpx;
margin-left: 40%;
}
.nicheng{
color:white;
}
到了這里,關(guān)于【微信小程序】使用微信API獲取用戶信息實(shí)現(xiàn)登錄的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!