vue3 + ts开发微信小程序获取用户头像昵称全流程

644 阅读1分钟

一、 基本流程

  • 通过应用生命周期判断用户是否登录,登录是否过期,如果不符合登录条件则进入登录页面
  • from表单上定义@submit="登录事件"
  • 通过定义按钮open-type="chooseAvatar",@chooseavatar="getChooseavatar"事件中的默认参数获取头像信息
  • 通过input中type="nickname"获取用户昵称信息,此处无法通过input,blur等事件获取,v-model绑定无效,在form绑定的登录事件中可以取得用户昵称信息(e.detail.value.nickname)
  • 判断用户是否提交合规的头像及昵称,如果不满足条件则拦截提示,满足条件则发送登录请求,存储登录信息,跳转页面,做出提示

二、 代码详解

核心代码如下:

<template>
	<!-- 提交表单 核心!!! -->
	<form  @submit="login"> 
	<!-- 背景及提交按钮 -->
	<view class="Login-page">
		<image mode="aspectFill" src="https://diancan-1252107261.cos.accelerate.myqcloud.com/yiliao/denglu-yemian.jpg">
		</image>
		<button form-type="submit">授权登陆</button>
	</view>
	<!-- 获取头像 -->
	<button  class="headSculpture" v-if="data.headSculptureUrl==''" open-type="chooseAvatar" @chooseavatar="getChooseavatar">
			+
	</button>
	<image :src="data.headSculptureUrl" v-if="data.headSculptureUrl!=''" mode="aspectFill" class="headSculpture"/>
	<!-- 获取昵称 -->
    <input  type="nickname" class="getUserName" placeholder="请输入昵称" name="nickname"/>  
	</form>  
</template>


<script lang='ts' setup>
// 1.引入基础模块
import { reactive } from 'vue'
import { reqLogin } from '@/serve/api'
let  data=reactive({
	headSculptureUrl: '',
})
// 获取用户头像
function getChooseavatar(e:any){	
	data.headSculptureUrl=e.detail.avatarUrl
}
// 登录提交按钮
async function getUserName(e:any) {
	// 判断用户昵称和头像是否填写 信息不全则拦截提示
	if(data.headSculptureUrl==''||e.detail.value.nickname==''){
		return uni.showToast({
			title: '请填写头像昵称'
		})
	}
	// 发送登录请求
	let result = await reqLogin({
				appid: 'appid',
				secret: '开发者秘钥',
				nickName: e.detail.value.nickname,
				avatarUrl:  data.headSculptureUrl,
				code: uni.getStorageSync('code')
			}).catch(err => {
				console.error(err)
			})
			// 请求成功则存储登录信息
			uni.setStorageSync('userInfo', result)
			// 跳转至主页
			uni.reLaunch({
				url:'/pages/index/index'
			})
			// 登录成功提示
			setTimeout(()=>{
			uni.showToast({
				title: '授权登录成功',
				icon: 'success',
				mask: true
			})
			},1000)
}
</script>
<style scoped>
.getUserName {
	position: absolute;
	left: 50%;
	top: 500rpx;
	transform: translate(-50%, 0);
	text-align: center;
}
.headSculpture {
	width: 100rpx ;
	height: 100rpx ;
	text-align: center;
	line-height: 100rpx;
	background-color: #ccc;
	font-size: 60rpx;
	position: absolute;
	left: 50%;
	top: 300rpx;
	transform: translate(-50%, 0);
	border-radius: 50%;
}
.Login-page {
	position: relative;
	height: 100vh;
	overflow: hidden;
}

.Login-page image {
	width: 100%;
	height: 100%;
}

.Login-page button {
	position: absolute;
	left: 50%;
	transform: translate(-50%, -50%);
	bottom: 30%;
	background-color: #2c76ef;
	color: #ffffff;
	padding: 0 100rpx;
	font-size: 35rpx;
}
</style>