一、 基本流程
- 通过应用生命周期判断用户是否登录,登录是否过期,如果不符合登录条件则进入登录页面
- 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>
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>