<template>
<div class="login-box">
<a-form-model :model="user" :rules="rules" ref="loginForm">
<a-form-model-item prop="username">
<a-input
placeholder="请输入账户"
v-model="user.username"
>
<a-icon slot="prefix" type="user" />
</a-input>
</a-form-model-item>
<a-form-model-item prop="password">
<a-input-password
placeholder="请输入账户密码"
v-model="user.password"
>
<a-icon slot="prefix" type="lock" />
</a-input-password>
</a-form-model-item>
<a-form-model-item prop="code">
<div class="code-box">
<a-input
placeholder="请输入验证码"
v-model="user.code"
>
<a-icon slot="prefix" type="safety" />
</a-input>
<img :src="codeImg" alt="" @click="refGetImg" />
</div>
</a-form-model-item>
<a-button type="primary" @click="loginClick"> 登录 </a-button>
</a-form-model>
</div>
</template>
<script lang="ts">
import { Vue , Component} from 'vue-property-decorator';
export interface InterfaceLogin{
code:string ;
username:string;
password:string;
uuid:string | null;
}
@Component({
name:'login',
})
export default class login extends Vue {
private user:InterfaceLogin = {
username:'' ,
password:'' ,
code:'',
uuid:'',
};
private codeImg = '' ;
private rules = {
username:[
{ required:true , message:'请输入账户',trigger:['change','blur'] },
],
password: [
{ required: true, message: '请输入密码', trigger: ['change', 'blur'] },
],
code: [
{ required: true, message: '请输入验证码', trigger: ['change', 'blur'] },
],
};
created() {
/** 清空 Session Storage 的值 */
sessionStorage.clear();
/** 获取验证码 */
this.refGetImg();
};
/** 获取验证码 */
private async refGetImg(){
const res = await getCode() //后台返回数据
if(res.status === 200){
this.codeImg = res.data.img
this.user.uuid = res.data.uuid
}
};
/** 登录 */
private async loginClick(){
(this.$refs.loginForm as any).validate(async (valid: any) => {
if (valid) {
const res = await postLogin(this.user); //调接口
if (res.code === 200) {
// 如果登录成功那么清楚本地数据使页面干净
sessionStorage.clear();
sessionStorage.setItem('Token', res.data.token); // 本地存取Token
sessionStorage.setItem('somUser', JSON.stringify(res.data.user)); // 本地存取个人信息
this.$router.push({ //跳转到主页面
path: '/home',
});
// 清空数据
this.user = {
code: '',
password: '',
username: '',
uuid: '',
};
} else {
this.$message.warning(res.message);
this.user.code = '';
// 如果失败更新验证码
this.refGetImg();
}
} else {
console.log('error submit!!');
return false;
}
});
};
}
</script>
VUE+TS+AntdVue验证码登录框实现
最新推荐文章于 2025-04-03 14:51:03 发布
这是一个使用Vue.js和TypeScript编写的登录组件示例,包含用户名、密码和验证码输入字段,以及登录按钮。组件利用了Ant Design Vue库进行UI设计。当用户点击登录时,会触发验证并调用后端接口进行登录操作。登录成功后,会清除本地SessionStorage,并存储Token和用户信息,然后重定向到主页;登录失败则重新获取验证码。
599

被折叠的 条评论
为什么被折叠?



