html
复制代码
<template>
<el-form :model="user" :rules="rules" ref="userForm" class="login" label-width="auto" style="max-width: 600px">
<el-form-item label="用户名" prop="name" >
<el-input v-model="user.name" id="name" placeholder="请输入用户名" />
</el-form-item>
<el-form-item label="密码" prop="pass">
<el-input v-model="user.pass" id="pass" placeholder="请输入密码"/>
</el-form-item>
<el-form-item label="验证码" prop="captcha">
<el-input v-model="user.captcha" id="captcha" placeholder="请输入验证码"/>
<img :src="captchaUrl" alt="验证码" @click="refreshCaptcha">
</el-form-item>
<el-form-item>
<el-button type="primary" @click="onSubmit" class="btn">登录</el-button>
</el-form-item>
</el-form>
</template>
<script lang="ts" setup>
import {onMounted, reactive, ref} from 'vue'
import Schema from "async-validator";
import {ElMessage} from "element-plus";
import axios from "axios";
// 响应式的对象
const user = reactive({
name: '',
pass: '',
captcha:''
})
// 设置验证规则
const rules = {
name: [
{ required: true, message: '请输入用户名', trigger: 'blur' },
{ min: 3, max: 30, message: '长度在 3 到 30 个字符', trigger: 'blur' },
],
pass: [{ required: true, message: '请输入密码', trigger: 'blur' }],
}
// 创建对表单的引用
const userForm = ref(null);
// 点击登录按钮的时候,验证是否满足rules规则
const onSubmit = () => {
if (userForm.value){
userForm.value.validate((valid: boolean)=>{
if (valid){
//验证通过,执行登录逻辑
console.log(user);
ElMessage.success("登录成功")
}else {
//表单验证未通过,显示错误信息
ElMessage.error("请检查输入的内容")
return false
}
})
}
}
// 验证码
// 使用 ref 创建响应式数据
const captchaUrl = ref('');
// 刷新验证码
const refreshCaptcha = ()=>{
axios.get('http://localhost:8080/captcha',{responseType : 'blob'})
.then(response =>{
captchaUrl.value = URL.createObjectURL(new Blob([response.data]));
})
.catch(error=>{
console.log("获取验证码失败",error)
})
}
// 组件挂载时加载验证码
onMounted(()=>{
refreshCaptcha();
})
</script>