当前位置:网站首页>Applet get user avatar and nickname
Applet get user avatar and nickname
2022-07-03 03:27:00 【Water W】
This article references B Stop video Applet combat project - Food Therapy Workshop _ Bili, Bili _bilibili
Catalog
Method 2 , This example is shown in method 2
Method 1
(1)wxml
<!--pages/contact/contact.wxml-->
Get user avatar and nickname -->
<!-- <view class="userInfo">
<view class="img"><open-data class="logo" type="userAvatarUrl"></open-data></view>
<open-data type="userNickName"></open-data>
</view>
Method 2 : This example is shown in method 2 , Through global variables globalData To read
1. To write contact page
(1)wxml
<!--pages/contact/contact.wxml-->
<view class="userInfo">
<button wx:if='{
{isShow}}' open-type="getUserInfo" bindgetuserinfo="getUserInfo"> Get avatars and nicknames </button>
<view wx:else>
<view class='img'><image class="logo" src="{
{userInfo.avatarUrl}}" alt=""/></view>
<view>{
{userInfo.nickName}}</view>
</view>
</view>(2)js
// pages/contact/contact.js
Page({
/**
* Initial data of the page
*/
data: {
isShow: true, // Display button
userInfo: '', // Store user information
},
// 1. Click button , Authorized avatar and nickname
getUserInfo(e) {
console.log(e);
this.setData({
userInfo : e.detail.userInfo,
isShow : false
})
},
/**
* Life cycle function -- Monitor page loading
*/
onLoad(options) {
},
/**
* Life cycle function -- Listening page first rendering completed
*/
onReady() {
},
/**
* Life cycle function -- Monitor page display
*/
onShow() {
},
/**
* Life cycle function -- Monitor page hidden
*/
onHide() {
},
/**
* Life cycle function -- Monitor page uninstall
*/
onUnload() {
},
/**
* Page related event handler -- Monitor user pull-down action
*/
onPullDownRefresh() {
},
/**
* Handling function of page pull bottom event
*/
onReachBottom() {
},
/**
* Users click the upper right corner to share
*/
onShareAppMessage() {
}
})(3)wxss
/* pages/contact/contact.wxss */
page {
background: #f5f5f5;
}
.userInfo {
padding: 10px;
background: #fff;
display: flex;
align-items: center;
}
.img .logo {
width: 180rpx;
height: 180rpx;
border-radius: 50%;
overflow: hidden;
border: 1px solid #ccc8c8;
display: block;
}2. Show the effect
(1) After the compilation , The page is shown as follows ,

(2) Click on “ Get avatars and nicknames ” Button , The page is shown as follows ,

problem : Every time you enter, you need to click “ Authorized user avatar and nickname ” Button .
3. Optimize
The user clicks : Get avatars and nicknames
- 1.button Trigger button click event
- 2. Defined function , obtain e.detail Get the nickname of the avatar
- 3. Refresh the page -- To enter again, you need to click the button . hope : Previously authorized , Get avatars and nicknames directly
- (1) The local store : After getting the user's Avatar and nickname , Store data locally .
- shortcoming : Data fixed , Will not update
- (2) Recapture : recommend . stay app.js Global access , Page sharing data .
- Get whether the user has been authorized before . If the information has been authorized before , Then get the avatar and nickname directly ; Otherwise, the first entry makes , Jump to the acquisition interface , Guide user authorization .
To write app.js
Be careful : Store user information in global variables , The current page cannot be used . That is, if I go directly to the present contact page ( Don't go to the home page first ), Then the current page contact The page can't get user information . Because the request data is asynchronous , If the asynchronous global cannot read , So you need to be in app.js Return data through functions in .
(1) open app.js, Compiling ,
// app.js
App({
onLaunch() {
// Demonstrate local storage capabilities
const logs = wx.getStorageSync('logs') || []
logs.unshift(Date.now())
wx.setStorageSync('logs', logs)
// Enter applet , Get whether the user is authorized before
// 1. Get the user's current settings . Only the permissions that the applet has requested from the user will appear in the return value .
wx.getSetting({
success:res=>{
console.log(res);
// Judge reswx.authSetting Does it include userInfo = true
if (res.authSetting['scope.userInfo']){ // Authorized
console.log(" User information has been authorized before , Direct access to ")
// Get the applet api, Get user information
wx.getUserInfo({
success:result=>{
console.log(' User information ',result)
// After obtaining the user information , Store to global variables globalData
this.globalData.userInfo = result.userInfo
// If the asynchronous global cannot read , Then the function returns data
if(this.callback){
this.callback(result.userInfo)
}
}
})
} else{
// Without authorization -- Jump to the authorization page
wx.showToast({
title: ' No authorization before , Please check the applet after authorization ',
})
// wx.switchTab({
// url: 'pages/contact/contact',
// })
}
}
})
},
globalData:{
userInfo:''
}
})
To write contact page
(2) First, in the contact.js Add this line of code , Then write ,

// pages/contact/contact.js
const app = getApp();
Page({
/**
* Initial data of the page
*/
data: {
isShow: true, // Display button
userInfo: '', // Store user information
},
// 1. Click button , Authorized avatar and nickname
getUserInfo(e) {
console.log(e);
this.setData({
userInfo : e.detail.userInfo,
isShow : false
})
},
/**
* Life cycle function -- Monitor page loading
*/
onLoad(options) {
// obtain app.js Global variables globalData User information for , If there is data, render the authorization information , There is no non rendering
if (app.globalData.userInfo){
console.log(' Global variable authorization information exists ')
this.setData({userInfo:app.globalData.userInfo,isShow:false})
}else{
// If the asynchronous global cannot read , Then by giving app Object definition function , receive data
app.callback=res=>{
console.log(res)
this.setData({userInfo:app.globalData.userInfo,isShow:false})
}
}
},
/**
* Life cycle function -- Listening page first rendering completed
*/
onReady() {
},
/**
* Life cycle function -- Monitor page display
*/
onShow() {
},
/**
* Life cycle function -- Monitor page hidden
*/
onHide() {
},
/**
* Life cycle function -- Monitor page uninstall
*/
onUnload() {
},
/**
* Page related event handler -- Monitor user pull-down action
*/
onPullDownRefresh() {
},
/**
* Handling function of page pull bottom event
*/
onReachBottom() {
},
/**
* Users click the upper right corner to share
*/
onShareAppMessage() {
}
})(3)contact.wxss and contact.wxml unchanged
/* pages/contact/contact.wxss */
page {
background: #f5f5f5;
}
.userInfo {
padding: 10px;
background: #fff;
display: flex;
align-items: center;
}
.img .logo {
width: 180rpx;
height: 180rpx;
border-radius: 50%;
overflow: hidden;
border: 1px solid #ccc8c8;
display: block;
}<!--pages/contact/contact.wxml-->
<!-- The user clicks : Get avatars and nicknames
1.button Trigger button click event
2. Defined function , obtain e.detail Get the nickname of the avatar
3. Refresh the page -- To enter again, you need to click the button . hope : Previously authorized , Get avatars and nicknames directly
The local store : After getting the user's Avatar and nickname , Store data locally
shortcoming : Data fixed , Will not update
Recapture : recommend
-->
<view class="userInfo">
<button wx:if='{
{isShow}}' open-type="getUserInfo" bindgetuserinfo="getUserInfo"> Get avatars and nicknames </button>
<view wx:else>
<view class='img'><image class="logo" src="{
{userInfo.avatarUrl}}" alt=""/></view>
<view>{
{userInfo.nickName}}</view>
</view>
</view>
Show the effect :
(1) Perform normal compilation , By default, enter the home page first , You can see console The debugger prints “ User information has been authorized before , Direct access to ”,

(2) Enter again contact page , You can see “ Global variable authorization information exists ” ,

(3) After emptying the cache , Perform normal compilation again , You will find that there is no “userInfo:true”, and contact The page shows “ Get user avatar and nickname ” Button .
边栏推荐
- Limit of one question per day
- UMI route interception (simple and rough)
- 模型转换onnx2engine
- 小程序获取用户头像和昵称
- 文件重命名
- Use three JS make a simple 3D scene
- [Chongqing Guangdong education] cultural and natural heritage reference materials of China University of Geosciences (Wuhan)
- C programming learning notes [edited by Mr. Tan Haoqiang] (Chapter III sequence programming) 05 data input and output
- labelimg生成的xml文件转换为voc格式
- Section 26 detailed explanation and demonstration of IPSec virtual private network configuration experiment - simulation experiment based on packettracer8.0
猜你喜欢

Agile certification (professional scrum Master) simulation exercise-2

ffmpeg下载安装教程及介绍

MySql实战45讲【索引】

Docker install MySQL
![C programming learning notes [edited by Mr. Tan Haoqiang] (Chapter III sequence programming) 03 operators and expressions](/img/4a/1df03d9f3315debb4c335260ed39f2.jpg)
C programming learning notes [edited by Mr. Tan Haoqiang] (Chapter III sequence programming) 03 operators and expressions

Section 26 detailed explanation and demonstration of IPSec virtual private network configuration experiment - simulation experiment based on packettracer8.0

Bid farewell to artificial mental retardation: Mengzi open source project team received RMB 100 million financing to help NLP develop

Introduction to mongodb

MySql實戰45講【SQL查詢和更新執行流程】

Pat class B "1104 forever" DFS optimization idea
随机推荐
用Three.js做一個簡單的3D場景
Hi3536c v100r001c02spc040 cross compiler installation
Basic operations of mongodb [add, delete, modify, query]
FileZilla Client下载安装
将时间戳转为指定格式的时间
Use three JS make a simple 3D scene
小程序获取用户头像和昵称
C # webrequest post mode, based on "basic auth" password authentication mode, uploads files and submits other data using multipart / form data mode
Vs Code configure virtual environment
labelme标记的文件转换为yolov5格式
The idea cannot be loaded, and the market solution can be applied (pro test)
C # general interface call
com. fasterxml. jackson. databind. Exc.invalidformatexception problem
[combinatorics] Application of exponential generating function (multiple set arrangement problem | different balls in different boxes | derivation of exponential generating function of odd / even sequ
Spark on yarn resource optimization ideas notes
[mathematical logic] normal form (conjunctive normal form | disjunctive normal form | major item | minor item | maximal item | minor item | principal conjunctive normal form | principal disjunctive no
Limit of one question per day
Find the storage address of the elements in the two-dimensional array
Edit and preview in the back pipe to get the value writing method of the form
The difference between componentscan and componentscans