Vue实现忘记密码模块
实现忘记密码模块的核心逻辑
在Vue中实现忘记密码功能通常需要以下关键步骤:用户输入邮箱/手机号、发送验证码、验证身份、重置密码。以下是一个完整实现方案:
前端界面设计
创建ForgotPassword.vue组件,包含表单结构和验证逻辑:

<template>
<div class="forgot-password">
<form @submit.prevent="handleSubmit">
<div v-if="!showResetForm">
<input v-model="email" placeholder="注册邮箱" />
<button @click="sendVerificationCode">获取验证码</button>
<input v-model="verificationCode" placeholder="验证码" />
<button type="submit">验证身份</button>
</div>
<div v-else>
<input v-model="newPassword" type="password" placeholder="新密码" />
<input v-model="confirmPassword" type="password" placeholder="确认密码" />
<button type="submit">重置密码</button>
</div>
</form>
</div>
</template>
表单验证逻辑
使用Vuelidate或自定义验证规则确保输入有效性:
data() {
return {
email: '',
verificationCode: '',
newPassword: '',
confirmPassword: '',
showResetForm: false,
countdown: 0
}
},
validations: {
email: { required, email },
verificationCode: { required, minLength: minLength(6) },
newPassword: {
required,
minLength: minLength(8),
strongPassword: value => /[A-Z]/.test(value) && /[0-9]/.test(value)
}
}
发送验证码功能
实现验证码发送和倒计时功能:

methods: {
async sendVerificationCode() {
if (this.countdown > 0) return;
try {
await axios.post('/api/auth/send-reset-code', {
email: this.email
});
this.countdown = 60;
const timer = setInterval(() => {
this.countdown--;
if (this.countdown <= 0) clearInterval(timer);
}, 1000);
} catch (error) {
alert('发送失败: ' + error.response.data.message);
}
}
}
密码重置API调用
验证通过后提交新密码到后端:
async handleSubmit() {
if (!this.showResetForm) {
try {
await axios.post('/api/auth/verify-reset-code', {
email: this.email,
code: this.verificationCode
});
this.showResetForm = true;
} catch (error) {
alert('验证失败: ' + error.response.data.message);
}
} else {
if (this.newPassword !== this.confirmPassword) {
alert('两次输入密码不一致');
return;
}
try {
await axios.post('/api/auth/reset-password', {
email: this.email,
newPassword: this.newPassword
});
alert('密码重置成功');
this.$router.push('/login');
} catch (error) {
alert('重置失败: ' + error.response.data.message);
}
}
}
安全增强措施
- 密码复杂度要求:至少8位,包含大小写字母和数字
- 验证码有效期限制(后端实现)
- 防止暴力破解:限制验证码尝试次数
- 使用HTTPS传输敏感数据
- 前端输入过滤防止XSS攻击
后端接口规范
前端需要对接的后端API通常包括:
POST /api/auth/send-reset-code # 发送验证码
POST /api/auth/verify-reset-code # 验证验证码
POST /api/auth/reset-password # 提交新密码
用户体验优化
- 添加加载状态指示器
- 验证码发送成功提示
- 密码重置成功自动跳转
- 移动端友好布局
- 错误信息的友好展示
实现时建议结合具体项目需求调整流程,例如支持手机号验证或添加安全问题验证等备用验证方式。






