【小程序】新版uniapp登录流程以及获取头像和昵称

众所周知,小程序新版登录无法拿到头像和昵称!

这篇文章讲解如何获取到微信用户昵称和头像
成品效果
  • 步骤一,点击登录,获取token

  • 在这里插入图片描述

  • 步骤二,登录按钮隐藏,展示上传按钮

  • 在这里插入图片描述

  • 步骤三,点击上传按钮

  • 在这里插入图片描述

  • 步骤四上传按钮隐藏,展示一下按钮

  • 步骤五,点击输入框,获取用户昵称

  • 在这里插入图片描述

HTML页面
<!-- 登录 -->
<view class="authorization" @click="getUser" v-if="isLogin==1">微信授权一键登录</view>


<!-- 获取用户头像 -->
<button class="authorization" type="default" open-type="chooseAvatar" @chooseavatar="chooseavatar" v-if="isLogin==2">上传微信头像</button>


<!-- 获取用户名称 -->
<input id="nickname-input" v-model="nickname" v- class="authorization white" type="nickname" placeholder="请输入用户昵称" v-if="isLogin==3">


<!-- 进入程序 -->
<view class="authorization" @click="gouser" v-if="isLogin==3" style="margin-top: 24rpx;">进入程序</view>

<!-- 暂不登录-->
<view class="no_login" @click="back" v-if="isLogin==1">暂不登录</view>

步骤一:获取code,通过uni.login或者wx.login

methods: {
//获取code
	getcode() {
		let _this = this;
		wx.login({
			success(res) {
				if (res.code) {
					_this.code = res.code;
				} else {
					console.log('登录失败');
				}
			}
		});
	},
}
步骤二:code换取sessionKey,openid等信息,去登录,获取token

这里引用了uview组件库,注意,不是强制使用,你可以使用自己的接口使用方式

methods: {
//获取sessionKey
getUser(){
	uni.$u.http.post('/api/user/getSessionKey', {
					code: this.code
				}).then(ress => {
					console.log(ress, "key数据")
					if (ress.code == 1) {
						uni.$u.http.post('/api/user/wxMobileLogin', {
							sessionKey: ress.data.session_key,
							iv: e.detail.iv,
							encryptedData: e.detail.encryptedData,
							openid: ress.data.openid
						}).then(res => {
							if (res.code == 1) {
								let type = res.data.type
								uni.setStorageSync("token", res.data.token)
								uni.setStorageSync("userinfo", res.data)
								//进行的操作
						},1000)
					}
				}).catch(err => {
					uni.showToast({
					title: res.ms0g,
					icon: 'none',
					duration: 200
			});
		})
	}
}

步骤三:获取微信头像

//获取用户头像,获取到的头像是临时文件,要通过自己的上传接口上传到服务器
	chooseavatar(e) {
		console.log(e)
		this.avater = e.detail.avatarUrl
		this.$uploadFile(this.avater).then((image) => {
			console.log(image)
			this.avater = image.data.fullurl
		})
		this.isLogin = 3
	},
步骤四:获取微信昵称

闭坑指南
注意,微信开发者工具的原生点击获取昵称,无法采用获取dom的方法去实时刷新data里的数据,采用真机调试去input事件赋值!

  • 当你点了自己的昵称以后,发现此时页面上双向绑定的nickname你会发现无法拿到值
  • 通过节点获取节点内容
  • 当你想判断用户有没有输入内容的时候,可以通过trim().length获取长度来判断
步骤四:获取微信昵称
闭坑指南
注意,微信开发者工具的原生点击获取昵称,无法采用获取dom的方法去实时刷新data里的数据,采用真机调试去input事件赋值!

当你点了自己的昵称以后,发现此时页面上双向绑定的nickname你会发现无法拿到值
通过节点获取节点内容
当你想判断用户有没有输入内容的时候,可以通过trim().length获取长度来判断

二:
​​​​​​【小程序】新版uniapp登录流程以及获取头像和昵称_小程序_博主花神-华为开发者空间

微信小程序获取用户头像、昵称是比较常见的需求,之前是授权一键获取,后面官方改成分别获取了,在这里记录一下其用法。

技术栈:uni-app、Vue3(3.4.21)、TypeScript(4.9.5)、wot-design-uni(1.2.26)、UnoCSS(0.58.9

实现步骤

  • 模板布局

获取头像主要是设置按钮属性open-type="chooseAvatar" ,并通过@chooseavatar获取图片。昵称则主要是设置输入框属性 type="nickname",监听输入内容变化。

<view class="cell-group">
  <wd-cell-group border>
    <wd-cell title="用户头像">
      <button class="cell-wrapper" open-type="chooseAvatar" @chooseavatar="getUserProfile">
        <wd-img
          width="60rpx"
          height="60rpx"
          round
          mode="aspectFill"
          :src="avatarUrl || defaultAvatarImg"
        />
        <wd-icon custom-class="ml-10rpx!" name="arrow-right1" size="28rpx"></wd-icon>
      </button>
    </wd-cell>
  </wd-cell-group>
  <wd-cell-group border>
    <wd-cell custom-class="nick-name" title="用户昵称" :value="nickName">
      <view class="flex justify-end items-center w380rpx">
        <input
          type="nickname"
          maxlength="20"
          class="cell-wrapper color-#777777 text-28rpx mr8rpx text-right"
          v-model="nickName"
          placeholder="请输入用户昵称"
          @change="handleChange"
        />
        <wd-img width="28rpx" height="28rpx" mode="aspectFill" :src="editDown" />
      </view>
    </wd-cell>
  </wd-cell-group>
</view>
  • 脚本代码

/** 用户头像 */
const avatarUrl = ref('https://xxx.png')
 
/** 获取用户头像 */
const getUserProfile = async (e) => {
  // 注意:这里是微信给我们返回图片的临时地址,实际开发中还需要上传图片到服务器
  avatarUrl.value = e.detail.avatarUrl
  // 业务操作:如更新头像到服务器
  console.log('操作成功...')
}
 
/** 用户昵称的正则表达式验证:1-20个字符 */
const nickNameExp = /^(?! *$)[\s\S]{1,20}$/
 
/** 用户昵称 */
const nickName = ref('')
 
/** 用户昵称输入框改变 */
const handleChange = debounce((e) => {
  const nickNameInput = e.detail.value.trim()
  if (nickNameInput === userStore.userInfo.nickName) return
  if (!nickNameExp.test(nickNameInput)) {
    console.log('用户昵称格式有误')
    return
  }
  // 业务操作:如更新昵称到服务器
  console.log('操作成功...')
}, 300)
  • CSS样式

.cell-group {
  padding: 32rpx;
  margin-top: 224rpx;
 
  .cell-wrapper {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    padding: 0;
    line-height: 1;
    background: none;
 
    &::after {
      border: none;
    }
  }
 
  .nick-name {
    color: #2f3032;
    :deep(.wd-cell__right) {
      flex: none !important;
    }
  }
 
  :deep(.wd-cell-group) {
    margin-top: 32rpx;
    overflow: hidden;
    border: 2rpx solid #d9e1e9;
    border-radius: 20rpx;
  }
 
  :deep(.wd-cell__wrapper) {
    align-items: center;
    height: 96rpx;
    padding: 28rpx 0;
  }
 
  :deep(.wd-cell__right) {
    padding-right: 32rpx;
  }
 
  :deep(.wd-cell__title) {
    --wot-cell-title-fs: 28rpx;
    color: #2f3032;
  }
 
  :deep(.wd-cell__value) {
    --wot-cell-value-fs: 27rpx;
 
    color: rgb(0 0 0 / 60%);
  }
 
  :deep(.wd-cell__arrow-right) {
    --wot-cell-arrow-size: 30rpx;
 
    color: rgb(0 0 0 / 60%);
  }
}

实现效果
获取头像:

获取/修改昵称:


                        
原文链接:https://blog.csdn.net/cjsnyxz/article/details/144380186

三:

微信小程序头像昵称填写

<template>
    <view class="container" :style="{'min-height':screenHeight+'px'}">
        <uni-nav-bar title="个人信息" statusBar fixed leftIcon="arrowleft" @clickLeft="clickBack"></uni-nav-bar>
        <view class="content_view">
            <button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
                <image class="avatar" :src="avatarUrl"></image>
            </button>
            <input type="nickname" class="weui-input" placeholder="请输入昵称" maxlength="15" :value="nickName"
                @change="getNickname" />
        </view>
        <view class="bottom_view">
            <view class="report_view" @click="submit">
                <text class="report_text">确认修改</text>
            </view>
        </view>
    </view>
</template>
<script>
    const defaultAvatarUrl =
        'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
    import {
        uploadTheImg,
    } from "@/utils/index.js";
    import {
        updateNickNameAndHeadImg
    } from '@/service/base-service.js'

    export default {
        data() {
            return {
                userInfo: {},
                avatarUrl: defaultAvatarUrl,
                nickName: "",
            }
        },
        created() {
            this.userInfo = uni.getStorageSync('memberInfo');
            this.nickName = this.userInfo.nickName
            this.avatarUrl = this.userInfo.headImage
            console.log("userInfo", this.userInfo)
        },
        mounted() {

        },
        methods: {
            clickBack() {
                uni.navigateBack();
            },
            getNickname(e) {
                console.log("getNickname", e.detail.value)
                this.nickName = e.detail.value
                this.checkNickName()
            },
            checkNickName() {
                if (!this.nickName) {
                    uni.showToast({
                        title: '请输入昵称',
                        icon: 'none'
                    })
                    return false
                }
                let str = this.nickName.trim();
                if (str.length == 0) {
                    uni.showToast({
                        title: '请输入正确的昵称',
                        icon: 'none'
                    })
                    return false
                }
                this.nickName = str
                // if ((/[^/a-zA-Z0-9\u4E00-\u9FA5]/g).test(str)) {
                //  uni.showToast({
                //      title: '请输入中英文和数字',
                //      icon: 'none'
                //  })
                //  return false
                // }
                return true
            },
            onChooseAvatar(e) {
                console.log("onChooseAvatar===", e)
                this.avatarUrl = e.detail.avatarUrl
                let params = {
                    urlType: "public",
                    prefix: "miniAvatar",
                };
                let that = this
                uploadTheImg([this.avatarUrl], params).then(res => {
                    // console.log("zsppppppppppppp========", res)
                    if (!res || res.length == 0) {
                        return
                    }
                    that.avatarUrl = res[0]
                })
            },
            submit() {
                console.log("submit提交", this.nickName, this.avatarUrl)
                // return
                if (!this.avatarUrl) {
                    uni.showToast({
                        title: '请上传头像',
                        icon: 'none'
                    })
                    return
                }
                if (!this.checkNickName()) {
                    return
                }
                let params = {
                    nickName: this.nickName,
                    headImage: this.avatarUrl,
                    memberId: this.userInfo.id,
                }
                console.log("params====", params)
                // return
                
                uni.showLoading({
                    title: '加载中',
                    mask: true
                })
                updateNickNameAndHeadImg(params).then(res => {
                    uni.hideLoading()
                    console.log("updateNickNameAndHeadImg==", res)
                    if (res.errorCode != 0) {
                        return
                    }
                    uni.showToast({
                        title: '修改成功',
                        icon: 'none'
                    })
                    this.userInfo.nickName = this.nickName
                    this.userInfo.headImage = this.avatarUrl
                    uni.setStorageSync('memberInfo', this.userInfo)
                    setTimeout(function() {
                        uni.$emit("userInfoRefresh", {
                            isRefresh: true,
                        });
                        uni.navigateBack();
                    }, 2000);
                }, err => {
                    uni.hideLoading()
                })

            },
        }
    }
</script>
<style lang='scss'>
    .container {
        display: flex;
        flex-direction: column;
    }

    /* 边框样式 */
    button::after {
        border: 0;
    }

    .content_view {
        display: flex;
        flex-direction: column;
        align-items: center;
        width: 100%;
        margin-top: 68px;
        position: relative;
        /* background-color: #F6F6FC; */
    }

    .avatar-wrapper {
        width: 100px;
        height: 100px;
        padding: 0 !important;
        margin: 0 !important;
        border-radius: 100px;
    }

    .avatar {
        width: 100px;
        height: 100px;
        border-radius: 100px;
        border-style: solid;
        border-width: 1px;
        border-color: #d6d6d5;
    }

    .weui-input {
        margin-top: 40px;
        width: 300px;
        height: 40px;
        background: #f4f4f6;
        line-height: 40px;
        text-align: center;
    }

    .bottom_view {
        position: fixed;
        bottom: 0;
        display: flex;
        flex-direction: row;
        justify-content: center;
        align-items: center;
        width: 100%;
        background-color: white;
        z-index: 20;
        padding-top: 10px;
        padding-bottom: constant(safe-area-inset-bottom);
        padding-bottom: env(safe-area-inset-bottom);
    }

    .report_view {
        display: flex;
        flex-direction: row;
        justify-content: center;
        align-items: center;
        width: 706rpx;
        height: 76rpx;
        background-color: #e60012;
        border-radius: 19px;
        margin-bottom: 10px;
    }

    .report_text {
        color: #fff;
        font-size: 15px;
    }
</style>

微信小程序头像昵称填写(uni-app) - 简书

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值