当前位置:网站首页>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 .
边栏推荐
- MySql实战45讲【SQL查询和更新执行流程】
- Basic operations of mongodb [add, delete, modify, query]
- 900w+ data, from 17s to 300ms, how to operate
- Limit of one question per day
- Edit and preview in the back pipe to get the value writing method of the form
- On the adjacency matrix and adjacency table of graph storage
- Bid farewell to artificial mental retardation: Mengzi open source project team received RMB 100 million financing to help NLP develop
- Docker install MySQL
- 文件重命名
- C # webrequest post mode, based on "basic auth" password authentication mode, uploads files and submits other data using multipart / form data mode
猜你喜欢

Docker install redis
![MySQL practice 45 lecture [row lock]](/img/71/344daddee537a96f0d38241e6896e1.png)
MySQL practice 45 lecture [row lock]

MongoDB簡介

MySql实战45讲【行锁】

Ansible简介【暂未完成(半成品)】
![MySQL practice 45 lecture [transaction isolation]](/img/a5/5420651d6be51e892976f02be8c43c.png)
MySQL practice 45 lecture [transaction isolation]

为什么线程崩溃不会导致 JVM 崩溃

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

900W+ 数据,从 17s 到 300ms,如何操作

Latest version of NPM: the "NPM" item cannot be recognized as the name of a cmdlet, function, script file, or runnable program. Please check
随机推荐
PAT乙级常用函数用法总结
45 lectures on MySQL [index]
【AI实战】应用xgboost.XGBRegressor搭建空气质量预测模型(一)
File rename
Réglez la hauteur et lancez le système. Currenttimemillis catton
com.fasterxml.jackson.databind.exc.InvalidFormatException问题
Change and access of median value of listening object
Find the storage address of the elements in the two-dimensional array
403 error displayed when vs cloning
Edit and preview in the back pipe to get the value writing method of the form
渤、黄海的潮汐特征
Introduction to mongodb
MySql实战45讲【事务隔离】
numpy之 警告VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences
3D drawing example
VS 2019配置tensorRT
PAT乙级“1104 天长地久”DFS优化思路
Pytorch multi card distributed training distributeddataparallel usage
Vs 2019 installation and configuration opencv
New programmers use the isXXX form to define Boolean types in the morning, and are discouraged in the afternoon?