去年微信調(diào)整了用戶信息獲取的api后,現(xiàn)在獲取用戶頭像和昵稱只能通過用戶自己觸發(fā)組件拿到用戶信息,那到底怎么做呢,下面跟大家分享一下我是怎么做的(新手,請多多包涵,有問題歡迎指出)
wxml:文章來源:http://www.zghlxwxcb.cn/news/detail-507362.html
<view class="top">
<button class="avatar-wrapper"
open-type="chooseAvatar"
bind:chooseavatar="onChooseAvatar"
>
<image class="avatar" src="{{avatarUrl}}"></image>
</button>
<van-icon name="edit" class="edit" />
<input type="nickname"
class="weui-input"
placeholder="微信用戶"
bind:change="getNickname"
maxlength="10"
value="{{username}}"/>
</view>
js:文章來源地址http://www.zghlxwxcb.cn/news/detail-507362.html
// 后端接口
import {getUserInfo,updateUserInfo,uploadPhoto} from '../api/profile/profile.js'
// 默認(rèn)頭像
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
Page({
/**
* 頁面的初始數(shù)據(jù)
*/
data: {
// 默認(rèn)頭像
avatarUrl: defaultAvatarUrl,
// 用戶昵稱
username:null,
openId:null,
userId:null
},
// 頭像上傳
onChooseAvatar(e){
// 回調(diào)事件返回的是圖片的臨時地址,會失效,我們需要調(diào)自己的上傳接口拿到圖片信息渲染到頁面
console.log(e.detail);
let avatarUrl = e.detail.avatarUrl
let openId = this.data.openId;
this.setData({
avatarUrl,
})
wx.uploadFile({
url: "http://192.168.x.xx.xxxx:/users/uploadImage", // 這里換成你們后端的上傳接口即可
method: 'POST',
filePath: avatarUrl,
name: 'file',
formData: {
openId: openId // 這里放你們接口所需要的參數(shù)
},
// 成功回調(diào)
success:(res)=>{
let result = JSON.parse(res.data); // JSON.parse()方法是將JSON格式字符串轉(zhuǎn)換為JSON對象
let newAvatarUrl = result.data[0].url; // 返回的圖片url
let userId = this.data.userId;
// 將返回的url替換調(diào)默認(rèn)的url,渲染在頁面上
this.setData({
avatarUrl:newAvatarUrl
})
/*
* 下面調(diào)保存頭像信息的接口(具體實(shí)現(xiàn)根據(jù)你們實(shí)際開發(fā)的需求)
*/
let fileInfo = {
userId:userId,
fileName:result.data[0].name,
fileUrl:result.data[0].url,
filePath:result.data[0].path,
}
uploadPhoto(fileInfo).then(res=>{
console.log(res);
})
},
});
},
// 用戶昵稱
getNickname: function (e){
let input = e.detail.value
this.setData({
username: input
})
// 修改用戶昵稱
let user = {
openId: this.data.openId,
userName: this.data.username
}
updateUserInfo(user).then(res=>{
this.queryInfo();
})
},
// 查詢用戶信息
queryInfo(){
let openId = wx.getStorageSync('login_info').openid
this.setData({
openId : openId
})
getUserInfo(openId).then(res=>{
console.log('查詢用戶信息',res);
if (res.data.code == 200) {
// 將查詢到用戶頭像、昵稱等信息覆蓋默認(rèn)值,然后渲染到頁面即可
this.setData({
username: res.data.data.userName,
userId:res.data.data.userId,
avatarUrl:res.data.data.fileUrl
})
}
})
},
/**
* 生命周期函數(shù)--監(jiān)聽頁面加載
*/
onLoad(options) {
// 頁面加載完畢之后查詢用戶信息
this.queryInfo();
},
})
到了這里,關(guān)于微信小程序使用頭像昵稱填寫完成頭像上傳的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!