Vue.js登录页面如何设置邮箱密码校验实现登录验证功能?
登录表单校验实现方案
你可以直接使用Vuetify内置的表单校验能力完成需求,修改后完整代码如下:
<template> <v-container> <div style="text-align: center;margin-bottom: 15px;"> <img src="../assets/images/girmiti.png" /> </div> <!-- 给表单加ref用于调用校验方法 --> <v-form ref="loginForm"> <v-row> <v-col offset-md="4"> <v-text-field v-model="email" type="email" placeholder="E-mail" rounded filled required style="width:400px;" :rules="emailRules" ></v-text-field> </v-col> </v-row> <v-row> <v-col offset-md="4"> <v-text-field v-model="password" type="password" placeholder="Password" required rounded filled style="width:400px;" :rules="passwordRules" ></v-text-field> </v-col> </v-row> <!-- 错误提示区域 --> <v-row v-if="loginError" style="margin-bottom: 12px;"> <v-col style="text-align: center;color: #f56c6c;"> 邮箱或密码错误,请输入正确的凭证 </v-col> </v-row> <v-row> <v-col style="text-align: center"> <v-btn color="success" class="mr-4" @click="validate"> Login </v-btn> </v-col> </v-row> </v-form> </v-container> </template> <script> export default { data: () => ({ email: "", password: "", loginError: false, // 配置允许登录的指定凭证,可自行修改 validCredentials: { email: "admin@girmiti.com", password: "Girmiti@2024" }, // 邮箱校验规则 emailRules: [ v => !!v || '邮箱不能为空', v => /^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/.test(v) || '请输入合法的邮箱格式' ], // 密码校验规则 passwordRules: [ v => !!v || '密码不能为空', v => v.length >= 6 || '密码长度不能少于6位' ] }), methods: { async validate() { // 先触发表单内置校验,判断格式是否符合要求 const isFormValid = await this.$refs.loginForm.validate() if (!isFormValid) return // 格式校验通过后,判断是否匹配指定的正确凭证 if (this.email === this.validCredentials.email && this.password === this.validCredentials.password) { this.loginError = false this.$router.push('/questionMaster') } else { this.loginError = true // 校验失败清空密码输入框,可按需开启 // this.password = '' } }, }, }; </script>
核心逻辑说明
- 表单校验会先触发输入框的rules规则校验,不满足格式要求时会直接在输入框下方提示错误,阻断后续逻辑
- 格式校验通过后才会和预设的指定凭证做匹配,匹配成功才会执行页面跳转,匹配失败则展示错误提示
- 你可以根据需求自行修改
validCredentials里的正确邮箱、密码值,也可以调整rules里的校验规则
内容的提问来源于stack exchange,提问作者T dhanunjay
相关产品推荐
相关产品推荐

