十一、登录注册页面 [element-plus 表单 & 表单校验]
注册登录 静态结构 & 基本切换
- 安装 element-plus 图标库
pnpm i @element-plus/icons-vue
- 静态结构准备
<script setup>
import { User, Lock } from '@element-plus/icons-vue'
import { ref } from 'vue'
const isRegister = ref(true)
</script>
<template>
<el-row class="login-page">
<el-col :span="12" class="bg"></el-col>
<el-col :span="6" :offset="3" class="form">
<el-form ref="form" size="large" autocomplete="off" v-if="isRegister">
<el-form-item>
<h1>注册</h1>
</el-form-item>
<el-form-item>
<el-input :prefix-icon="User" placeholder="请输入用户名"></el-input>
</el-form-item>
<el-form-item>
<el-input
:prefix-icon="Lock"
type="password"
placeholder="请输入密码"
></el-input>
</el-form-item>
<el-form-item>
<el-input
:prefix-icon="Lock"
type="password"
placeholder="请输入再次密码"
></el-input>
</el-form-item>
<el-form-item>
<el-button class="button" type="primary" auto-insert-space>
注册
</el-button>
</el-form-item>
<el-form-item class="flex">
<el-link type="info" :underline="false" @click="isRegister = false">
← 返回
</el-link>
</el-form-item>
</el-form>
<el-form ref="form" size="large" autocomplete="off" v-else>
<el-form-item>
<h1>登录</h1>
</el-form-item>
<el-form-item>
<el-input :prefix-icon="User" placeholder="请输入用户名"></el-input>
</el-form-item>
<el-form-item>
<el-input
name="password"
:prefix-icon="Lock"
type="password"
placeholder="请输入密码"
></el-input>
</el-form-item>
<el-form-item class="flex">
<div class="flex">
<el-checkbox>记住我</el-checkbox>
<el-link type="primary" :underline="false">忘记密码?</el-link>
</div>
</el-form-item>
<el-form-item>
<el-button class="button" type="primary" auto-insert-space
>登录</el-button
>
</el-form-item>
<el-form-item class="flex">
<el-link type="info" :underline="false" @click="isRegister = true">
注册 →
</el-link>
</el-form-item>
</el-form>
</el-col>
</el-row>
</template>
<style lang="scss" scoped>
.login-page {
height: 100vh;
background-color: #fff;
.bg {
background: url('@/assets/logo2.png') no-repeat 60% center / 240px auto,
url('@/assets/login_bg.jpg') no-repeat center / cover;
border-radius: 0 20px 20px 0;
}
.form {
display: flex;
flex-direction: column;
justify-content: center;
user-select: none;
.title {
margin: 0 auto;
}
.button {
width: 100%;
}
.flex {
width: 100%;
display: flex;
justify-content: space-between;
}
}
}
</style>
注册功能
实现注册校验(URL: http://localhost:5173/login)
【需求】注册页面基本校验
- 用户名非空,长度校验5-10位
- 密码非空,长度校验6-15位
- 再次输入密码,非空,长度校验6-15位
【进阶】再次输入密码需要自定义校验规则,和密码框值一致(可选)
注意:
- model 属性绑定 form 数据对象
const formModel = ref({
username: '',
password: '',
repassword: ''
})
<el-form :model="formModel" >
- v-model 绑定 form 数据对象的子属性
<el-input
v-model="formModel.username"
:prefix-icon="User"
placeholder="请输入用户名"
></el-input>
...
(其他两个也要绑定)
- rules 配置校验规则
<el-form :rules="rules" >
const rules = {
username: [
{ required: true, message: '请输入用户名', trigger: 'blur' },
{ min: 5, max: 10, message: '用户名必须是5-10位的字符', trigger: 'blur' }
],
password: [
{ required: true, message: '请输入密码', trigger: 'blur' },
{
pattern: /^\S{6,15}$/,
message: '密码必须是6-15位的非空字符',
trigger: 'blur'
}
],
repassword: [
{ required: true, message: '请再次输入密码', trigger: 'blur' },
{
pattern: /^\S{6,15}$/,
message: '密码必须是6-15的非空字符',
trigger: 'blur'
},
{
validator: (rule, value, callback) => {
if (value !== formModel.value.password) {
callback(new Error('两次输入密码不一致!'))
} else {
callback()
}
},
trigger: 'blur'
}
]
}
- prop 绑定校验规则
<el-form-item prop="username">
<el-input
v-model="formModel.username"
:prefix-icon="User"
placeholder="请输入用户名"
></el-input>
</el-form-item>
...
(其他两个也要绑定prop)
LoginPage.vue
源码(URL:http://localhost:5173/login
)
<script setup>
import { User, Lock } from '@element-plus/icons-vue'
import { ref } from 'vue'
const isRegister = ref(true)
// rulesForm 表单数据对象
// (整个的用于提交的form数据对象)
const formModel = ref({
username:'',
password:'',
repassword:'',
})
// 整个表单校验规则
//1、非空, 触发时机为失去焦点(blur),实时校验(change)
//2、长度校验
// 3、正则校验,pattern:正则规则 :\S非空字符
//4、自定义校验=>自己写逻辑校验(校验函数)
// validator:(rule,value,callback)
// (1)rule:当前校验规则相关的信息
// (2)value:所校验的表单元素目前的表单值
// (3)callback:无论成功还是失败,都需要callbak()
// - callback()校验成功
// - callback(new Error(错误信息))校验失败,error为错误信息
const rules ={
username:[
{required:true,message:'请输入用户名',trigger:'change'},
{min:5,max:10,message:'用户名必须是5-10个字符',trigger:'change'}
],
password:[
{required:true,message:'请输入密码',trigger:'change'},
{pattern:/^\S{6,15}$/,message:'密码必须是6-15位的非空字符',trigger:'blur'}
],
repassword:[
{required:true,message:'请输入密码',trigger:'change'},
{pattern:/^\S{6,15}$/,message:'密码必须是6-15位的非空字符',trigger:'blur'},
{
validator:(rule, value,callback)=>{
// 判断value和当前form中收集的password是否一致
if(value !== formModel.value.password){
callback(new Error('两次密码输入不一致'))
}
else{
callback() //就算校验成功也需要callback()
}
},
trigger:'blur'
}
]
}
</script>
<template>
<!--
1、结构相关
el-row表示一行
el-col 表示一列,span表示占据的宽度,offset表示左右间距
2、校验相关
(1)el-form=> :model "rulesForm" 绑定的是整个form的数据对象 {xxx,xxx,xxx}
(2)el-form => :rules 绑定的是整个rules规则对象 {xxx,xxx,xxx}
(3)表单元素 =》 v-model="ruleFormxxx" 给表单元素,绑定form的子属性
(4)prop配置生效的是哪个校验规则(和ruls中的字段要对应)
-->
<el-row class="login-page">
<el-col :span="12" class="bg"></el-col>
<el-col :span="6" :offset="3" class="form">
<!-- 注册 -->
<el-form
:model="formModel"
:rules="rules"
ref="form"
size="large"
autocomplete="off"
v-if="isRegister">
<el-form-item>
<h1>注册</h1>
</el-form-item>
<el-form-item prop="username">
<el-input v-model="formModel.username" :prefix-icon="User" placeholder="请输入用户名"></el-input>
</el-form-item>
<el-form-item prop="password">
<el-input
v-model="formModel.password"
:prefix-icon="Lock"
type="text"
placeholder="请输入密码"
></el-input>
</el-form-item>
<el-form-item prop="repassword">
<el-input
v-model="formModel.repassword"
:prefix-icon="Lock"
type="text"
placeholder="请输入再次密码"
></el-input>
</el-form-item>
<el-form-item>
<el-button class="button" type="primary" auto-insert-space>
注册
</el-button>
</el-form-item>
<el-form-item class="flex">
<el-link type="info" :underline="false" @click="isRegister = false">
← 返回
</el-link>
</el-form-item>
</el-form>
<!-- 登录 -->
<el-form ref="form" size="large" autocomplete="off" v-else>
<el-form-item>
<h1>登录</h1>
</el-form-item>
<el-form-item>
<el-input :prefix-icon="User" placeholder="请输入用户名"></el-input>
</el-form-item>
<el-form-item>
<el-input
name="password"
:prefix-icon="Lock"
type="password"
placeholder="请输入密码"
></el-input>
</el-form-item>
<el-form-item class="flex">
<div class="flex">
<el-checkbox>记住我</el-checkbox>
<el-link type="primary" :underline="false">忘记密码?</el-link>
</div>
</el-form-item>
<el-form-item>
<el-button class="button" type="primary" auto-insert-space
>登录</el-button
>
</el-form-item>
<el-form-item class="flex">
<el-link type="info" :underline="false" @click="isRegister = true">
注册 →
</el-link>
</el-form-item>
</el-form>
</el-col>
</el-row>
</template>
<style lang="scss" scoped>
.login-page {
height: 100vh;
background-color: #fff;
.bg {
background: url('@/assets/logo2.png') no-repeat 60% center / 240px auto,
url('@/assets/login_bg.jpg') no-repeat center / cover;
border-radius: 0 20px 20px 0;
}
.form {
display: flex;
flex-direction: column;
justify-content: center;
user-select: none;
.title {
margin: 0 auto;
}
.button {
width: 100%;
}
.flex {
width: 100%;
display: flex;
justify-content: space-between;
}
}
}
</style>
App.vue
<script setup>
</script>
<template>
<div>
<router-view></router-view>
</div>
</template>
<style lang="scss" scoped>
</style>
- 预览视图
注册前的预校验
需求:点击注册按钮,注册之前,需要先校验
- 通过 ref 获取到 表单组件
const form = ref()
<el-form ref="form">
- 注册之前进行校验
<el-button
@click="register"
class="button"
type="primary"
auto-insert-space
>
注册
</el-button>
const register = async () => {
await form.value.validate()
console.log('开始注册请求')
}
封装 api 实现注册功能
需求:封装注册api,进行注册,注册成功切换到登录
- 新建 api/user.js 封装
import request from '@/utils/request'
export const userRegisterService = ({ username, password, repassword }) =>
request.post('/api/reg', { username, password, repassword })
- 页面中调用
const register = async () => {
await form.value.validate()
await userRegisterService(formModel.value)
ElMessage.success('注册成功')
// 切换到登录
isRegister.value = false
}
eslintrc
中声明全局变量名, 解决 ElMessage 报错问题
module.exports = {
...
globals: {
ElMessage: 'readonly',
ElMessageBox: 'readonly',
ElLoading: 'readonly'
}
}
登录功能
实现登录校验
【需求说明】给输入框添加表单校验
- 用户名不能为空,用户名必须是5-10位的字符,失去焦点 和 修改内容时触发校验
- 密码不能为空,密码必须是6-15位的字符,失去焦点 和 修改内容时触发校验
操作步骤:
- model 属性绑定 form 数据对象,直接绑定之前提供好的数据对象即可
<el-form :model="formModel" >
- rules 配置校验规则,共用注册的规则即可
<el-form :rules="rules" >
- v-model 绑定 form 数据对象的子属性
<el-input
v-model="formModel.username"
:prefix-icon="User"
placeholder="请输入用户名"
></el-input>
<el-input
v-model="formModel.password"
name="password"
:prefix-icon="Lock"
type="password"
placeholder="请输入密码"
></el-input>
- prop 绑定校验规则
<el-form-item prop="username">
<el-input
v-model="formModel.username"
:prefix-icon="User"
placeholder="请输入用户名"
></el-input>
</el-form-item>
...
- 切换的时候重置
watch(isRegister, () => {
formModel.value = {
username: '',
password: '',
repassword: ''
}
})
登录前的预校验 & 登录成功
【需求说明1】登录之前的预校验
- 登录请求之前,需要对用户的输入内容,进行校验
- 校验通过才发送请求
【需求说明2】登录功能
- 封装登录API,点击按钮发送登录请求
- 登录成功存储token,存入pinia 和 持久化本地storage
- 跳转到首页,给提示
【测试账号】
-
登录的测试账号: shuaipeng
-
登录测试密码: 123456
PS: 每天账号会重置,如果被重置了,可以去注册页,注册一个新号
实现步骤:
- 注册事件,进行登录前的预校验 (获取到组件调用方法)
<el-form ref="form">
const login = async () => {
await form.value.validate()
console.log('开始登录')
}
- 封装接口 API
export const userLoginService = ({ username, password }) =>
request.post('api/login', { username, password })
- 调用方法将 token 存入 pinia 并 自动持久化本地
const userStore = useUserStore()
const router = useRouter()
const login = async () => {
await form.value.validate()
const res = await userLoginService(formModel.value)
userStore.setToken(res.data.token)
ElMessage.success('登录成功')
router.push('/')
}
“中秋快乐呀!”
下一期学习笔记会尽快更新的。