1、建立頁面load小程序
建立頁面load緩存
二、需求說明微信
登陸以前,【個人】頭像和文字顯示爲默認顯示。微信受權登陸成功以後,【個人】頭像和文字分別獲取微信頭像和微信名字。xss
三、代碼實現(微信受權登陸頁面)函數
一、load.wxmlflex
1 <view class="loadType"> 2 <button type="primary" bindtap="loadByWechat">微信受權登陸</button> 3 <button type="primary" plain="true" bindtap="loadByPhone">手機號碼登陸</button> 4 <button type="primary" plain="true" bindtap="loadByAccount">帳號密碼登陸</button> 5 </view>
二、load.wxssthis
1 .loadType{ 2 margin-top: 800rpx; 3 } 4 button{ 5 margin-top: 20rpx; 6 }
三、load.jsurl
1 Page({ 2 3 //微信受權登陸 4 loadByWechat(){ 5 wx.getUserProfile({ 6 desc: '用戶完善會員資料', 7 }) 8 .then(res=>{ 9 console.log("用戶容許了微信受權登陸",res.userInfo); 10 //注意:此時不能使用 wx.switchTab,不支持參數傳遞 11 wx.reLaunch({ 12 //將微信頭像和微信名稱傳遞給【個人】頁面 13 url: '/pages/me/me?nickName='+res.userInfo.nickName+'&avatarUrl='+res.userInfo.avatarUrl, 14 }) 15 //保存用戶登陸信息到緩存 16 wx.setStorageSync('userInfo', res.userInfo) 17 }) 18 .catch(err=>{ 19 console.log("用戶拒絕了微信受權登陸",err); 20 }) 21 }, 22 23 //跳轉到手機號碼登陸頁 24 loadByPhone(){ 25 wx.navigateTo({ 26 url: '/pages/loadByPhone/loadByPhone', 27 }) 28 }, 29 30 //跳轉到帳號密碼登陸頁 31 loadByAccount(){ 32 wx.navigateTo({ 33 url: '/pages/loadByAccount/loadByAccount', 34 }) 35 }, 36 37 })
四、代碼實現(個人頁面)spa
一、me.wxmlcode
1 <!--未登陸--> 2 <view class="load" wx:if="{{!loginOk}}"> 3 <image src="../../images/個人.png" bindtap="load"></image> 4 <text class="clickload" bindtap="load">點擊登陸</text> 5 </view> 6 <!--已登陸--> 7 <view wx:else> 8 <view class="load" > 9 <image src="{{avatarUrl}}" ></image> 10 <text class="clickload" >{{nickName}}</text> 11 </view> 12 <button class="exit" bindtap="exit" type="primary">退出登陸</button> 13 </view>
二、me.wxss
1 .load{ 2 background-color:#04BE02; 3 width: 100%; 4 height: 400rpx; 5 /*設置圖片和文字垂直居中對齊*/ 6 display: flex; 7 flex-direction: column; 8 justify-content: center; 9 align-items: center; 10 } 11 12 .load image{ 13 width: 200rpx; 14 height: 200rpx; 15 border-radius: 50%; 16 } 17 .load text{ 18 color:white; 19 } 20 .exit{ 21 width: 95%; 22 margin-top: 40rpx; 23 }
三、me.js
1 Page({ 2 3 /** 4 * 頁面的初始數據 5 */ 6 data: { 7 loginOk:true, 8 nickName:"", 9 avatarUrl:"", 10 }, 11 12 //頁面加載的時候,將load頁面傳過來的值獲取過來 13 onLoad: function (options) { 14 console.log("這裏的options",options); 15 this.setData({ 16 nickName:options.nickName, 17 avatarUrl:options.avatarUrl 18 }) 19 }, 20 21 //小程序聲明週期的可見性函數裏面來控制顯示 22 onShow(){ 23 let userInfo = wx.getStorageSync('userInfo') 24 console.log("個人緩存信息",userInfo); 25 if(userInfo){ 26 this.setData({ 27 loginOk:true, 28 nickName:userInfo.nickName, //從緩存中拿數據 29 avatarUrl:userInfo.avatarUrl 30 }) 31 }else{ 32 this.setData({ 33 loginOk:false 34 }) 35 } 36 }, 37 38 //點擊登陸 39 load(){ 40 wx.navigateTo({ 41 url: '/pages/load/load', 42 }) 43 }, 44 45 //退出登陸 46 exit(){ 47 wx.showModal({ 48 content:"肯定退出嗎" 49 }).then(res=>{ 50 if(res.confirm){ 51 console.log("用戶點擊了肯定"); 52 this.setData({ 53 loginOk:false 54 }) 55 //清空登陸的緩存 56 wx.setStorageSync('userInfo', null) 57 }else if(res.cancel){ 58 console.log("用戶點擊了取消"); 59 } 60 }) 61 }, 62 63 })
5、效果展現