在小程序开发中,获取用户基本信息是非常常见的需求。本文将介绍在 uniapp 中如何获取用户的基本信息,包括用户的昵称、头像等信息。
步骤一:开发组件
在登录组件中,设计了一个底部弹窗,通过点击按钮触发用户信息的获取。通过uniapp提供的uni.getUserInfo
和uni.getUserProfile
方法,实现了用户头像和昵称的获取功能。还实现了用户头像的上传功能,包括用户选择头像和将头像上传至服务器。
页面代码:
<template> <view> <view @touchmove.prevent.stop class="complete-info-popup"> <uni-popup ref="auth" type="bottom" :custom="true" :mask-click="false"> <view class="complete-info-wrap"> <view class="head"> <text class="title"> 获取您的昵称、头像 <template v-if="forceBindingMobileControl"> 、手机号 </template> </text> <text class="color-tip tips"> 获取用户头像、昵称 <template v-if="forceBindingMobileControl"> 、手机号 </template> 完善个人资料,主要用于向用户提供具有辨识度的用户中心界面 </text> <text class="iconfont icon-close color-tip" @click="cancelCompleteInfo"></text> </view> <view class="item-wrap"> <text class="label">头像</text> <button open-type="chooseAvatar" @chooseavatar="onChooseAvatar"> <image :src="avatarUrl ? avatarUrl : $util.getDefaultImage().head" @error="avatarUrl = $util.getDefaultImage().head" mode="aspectFill"></image> <text class="iconfont icon-right color-tip"></text> </button> </view> <view class="item-wrap"> <text class="label">昵称</text> <input type="nickname" placeholder="请输入昵称" v-model="nickName" @blur="blurNickName" maxlength="50" /> </view> <button type="default" class="save-btn" @click="saveMp">保存</button> </view> </uni-popup> </view> </view> </template>
script代码:
<script> import uniPopup from '../uni-popup/uni-popup.vue'; import auth from 'common/js/auth.js'; import Config from 'common/js/config.js'; export default { mixins: [auth], name: 'ns-login', components: { uniPopup }, data() { return { url: '', avatarUrl: '', // 头像预览路径 headImg: '', // 头像上传路径 nickName: '', // 昵称 canUseGetUserProfile: false }; }, created() { if (uni.getUserProfile) { this.canUseGetUserProfile = true; } if (uni.getStorageSync('authInfo')) { let data = uni.getStorageSync('authInfo'); if (data.authInfo) this.authInfo = data.authInfo; if (data.userInfo) this.userInfo = data.userInfo; this.checkOpenidIsExits(); } // #ifdef MP this.getCode(() => { if (Object.keys(this.authInfo).length) { this.$api.sendRequest({ url: '/api/login/openidisexits', data: this.authInfo, success: res => { if (res.code >= 0 && res.data > 0) { this.isBind = true; } } }); } }); // #endif }, methods: { open(url){ if (url) this.url = url; this.$refs.auth.open(); }, close(){ this.$refs.auth.close(); }, bindgetuserinfo(e){ this.$refs.auth.close(); // #ifdef MP-WEIXIN if(uni.getUserProfile){ uni.getUserProfile({ desc: '授权登录', success: (res) => { uni.setStorage({ key: 'bindUserInfo', data: res.userInfo }); if (this.url) this.$util.redirectTo('/otherpages/login/login/login', { back: this.url }); else this.$util.redirectTo('/otherpages/login/login/login'); }, fail:(res) => { this.$refs.auth.close(); } }); }else{ if (e.detail.errMsg == 'getUserInfo:ok') { uni.setStorage({ key: 'bindUserInfo', data: e.detail.userInfo }); if (this.url) this.$util.redirectTo('/otherpages/login/login/login', { back: this.url }); else this.$util.redirectTo('/otherpages/login/login/login'); } } // #endif }, login(){ this.$refs.auth.close(); if (this.$util.isWeiXin()) { let redirect_url = ''; if (this.url) redirect_url = Config.h5Domain + '/otherpages/login/login/login?back=' + encodeURIComponent(this.url); else redirect_url = Config.h5Domain + '/otherpages/login/login/login'; this.$api.sendRequest({ url: '/wechat/api/wechat/authcode', data: { redirect_url }, success: res => { if (res.code >= 0) { location.href = res.data; } else { if (this.url) this.$util.redirectTo('/otherpages/login/login/login', { back: this.url }); else this.$util.redirectTo('/otherpages/login/login/login'); } }, fail: res => { if (this.url) this.$util.redirectTo('/otherpages/login/login/login', { back: this.url }); else this.$util.redirectTo('/otherpages/login/login/login'); } }) } else { if (this.url) this.$util.redirectTo('/otherpages/login/login/login', { back: this.url }); else this.$util.redirectTo('/otherpages/login/login/login'); } }, /** * 授权登录 */ authLogin(data, type = 'authLogin') { uni.showLoading({ title: '登录中' }); uni.setStorage({ key: 'authInfo', data: data }); if (uni.getStorageSync('source_member')) data.source_member = uni.getStorageSync('source_member'); this.$api.sendRequest({ url: '/api/register/authRegisterUser', data, success: res => { if (res.code >= 0) { uni.setStorage({ key: 'token', data: res.data.token, success: () => { this.$store.dispatch('getCartNumber'); this.$store.commit('setToken', res.data.token); this.cancelCompleteInfo(); } }); setTimeout(() => { uni.hideLoading(); }, 1000); } else { uni.hideLoading(); this.$util.showToast({ title: res.message }); } }, fail: () => { uni.hideLoading(); this.$util.showToast({ title: '登录失败' }); } }); }, onChooseAvatar(e) { this.avatarUrl = e.detail.avatarUrl; uni.getFileSystemManager().readFile({ filePath: this.avatarUrl, //选择图片返回的相对路径 encoding: 'base64', //编码格式 success: res => { let base64 = 'data:image/jpeg;base64,' + res.data; //不加上这串字符,在页面无法显示的哦 this.myUpload(base64); } }); }, blurNickName(e) { if (e.detail.value) this.nickName = e.detail.value; }, //上传返回图片 myUpload(base64) { let app_type = 'h5'; let app_type_name = 'H5'; // #ifdef MP app_type = 'weapp'; app_type_name = 'weapp'; // #endif uni.request({ url: this.$config.baseUrl + '/api/upload/headimgBase64', method: 'POST', data: { app_type: app_type, app_type_name: app_type_name, images: base64 }, header: { 'content-type': 'application/x-www-form-urlencoded;application/json' }, dataType: 'json', responseType: 'text', success: res => { if (res.data.code == 0) { this.headImg = res.data.data.pic_path; } else { this.$util.showToast({ title: res.message }); } }, fail: () => { this.$util.showToast({ title: '上传失败' }); } }); }, forceBindingMobileControl() { if (this.registerConfig && this.registerConfig.third_party == 1 && this.registerConfig.bind_mobile == 1) return true; else return false; }, cancelCompleteInfo() { if (this.$refs.completeInfoPopup) this.$refs.completeInfoPopup.close(); }, // 微信小程序保存数据 saveMp() { if (this.nickName.length == 0) { this.$util.showToast({ title: '请输入昵称' }); return; } let authData = {}; authData[this.authInfo.auth_tag] = this.authInfo.auth_openid; if (authData) Object.assign(authData, { nickName: this.nickName, avatarUrl: this.headImg }); uni.setStorageSync('authInfo', authData); this.authLogin(authData); }, checkOpenidIsExits() { if (Object.keys(this.authInfo).length) { uni.setStorage({ key: 'authInfo', data: { authInfo: this.authInfo, userInfo: this.userInfo } }); this.$api.sendRequest({ url: '/api/login/openidisexits', data: this.authInfo, success: res => { console.log(res) if (res.code >= 0 && res.data > 0) { this.isBind = true; } } }); } } } }; </script>
样式代码:
<style lang="scss"> .complete-info-popup { .complete-info-wrap { background: #fff; padding: 50rpx 40rpx 40rpx; .head { position: relative; border-bottom: 2rpx solid #eeeeee; padding-bottom: 20rpx; .title { font-size: 32rpx; display: block; } .tips { font-size: 28rpx; display: block; } .iconfont { position: absolute; right: 0; top: -30rpx; display: inline-block; width: 56rpx; height: 56rpx; line-height: 56rpx; text-align: right; font-size: 32rpx; font-weight: bold; } } .item-wrap { border-bottom: 2rpx solid #eeeeee; display: flex; align-items: center; padding: 16rpx 0; .label { font-size: 32rpx; margin-right: 40rpx; width: 100rpx; } button { background: transparent; margin: 0; padding: 0; border-radius: 0; flex: 1; text-align: left; display: flex; align-items: center; font-size: 32rpx; image { width: 100rpx; height: 100rpx; border-radius: 10rpx; overflow: hidden; } } .iconfont { flex: 1; text-align: right; font-size: 24rpx; } input { flex: 1; height: 80rpx; box-sizing: border-box; font-size: 32rpx; } .send { border: 2rpx solid $base-color; height: 60rpx; line-height: 60rpx; border-radius: 60rpx; font-size: 24rpx; text-align: center; padding: 0 40rpx; } .captcha { height: 80rpx; width: 200rpx; } .auth-login { width: calc(100% - 100rpx); height: 80rpx; line-height: 80rpx; border-radius: 80rpx; } } .save-btn { width: 280rpx; height: 90rpx; line-height: 90rpx; background-color: #07c160; color: #fff; margin: 40rpx auto 20rpx; } } } </style> <style scoped> /deep/ .reward-popup .uni-popup__wrapper-box { background: none !important; max-width: unset !important; max-height: unset !important; overflow: unset !important; } .complete-info-popup /deep/ .uni-popup__wrapper.bottom, .complete-info-popup /deep/ .uni-popup__wrapper.bottom .uni-popup__wrapper-box { border-top-left-radius: 30rpx !important; border-top-right-radius: 30rpx !important; } </style>
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。