vue实现忘记密码
Vue 实现忘记密码功能
忘记密码功能通常包含以下步骤:用户输入注册邮箱或手机号,系统发送验证码或重置链接,用户验证身份后设置新密码。以下是基于 Vue 的实现方案:
前端页面结构
使用 Vue 单文件组件(SFC)构建页面,分为三步流程:

- 输入账号(邮箱/手机)
- 验证身份(验证码或邮件链接)
- 重置密码
<template>
<div v-if="step === 1">
<input v-model="account" placeholder="邮箱/手机号">
<button @click="sendVerification">发送验证码</button>
</div>
<div v-if="step === 2">
<input v-model="code" placeholder="验证码">
<button @click="verifyCode">验证</button>
</div>
<div v-if="step === 3">
<input v-model="newPassword" type="password" placeholder="新密码">
<button @click="resetPassword">提交</button>
</div>
</template>
状态管理
使用 Vue 的 data 或 Pinia/Vuex 管理流程状态:

data() {
return {
step: 1,
account: '',
code: '',
newPassword: '',
timer: null,
countdown: 60
}
}
发送验证码
调用后端 API 发送验证码,并添加倒计时功能:
methods: {
async sendVerification() {
try {
await axios.post('/api/send-reset-code', { account: this.account });
this.startCountdown();
this.step = 2;
} catch (error) {
alert('发送失败: ' + error.response.data.message);
}
},
startCountdown() {
this.timer = setInterval(() => {
if (this.countdown <= 0) {
clearInterval(this.timer);
this.countdown = 60;
} else {
this.countdown--;
}
}, 1000);
}
}
验证与密码重置
验证用户输入的验证码,成功后允许重置密码:
methods: {
async verifyCode() {
const res = await axios.post('/api/verify-code', {
account: this.account,
code: this.code
});
if (res.data.valid) this.step = 3;
},
async resetPassword() {
await axios.post('/api/reset-password', {
account: this.account,
newPassword: this.newPassword
});
alert('密码已重置');
this.$router.push('/login');
}
}
安全注意事项
- 前端需做基础验证(如邮箱格式、密码强度),但最终验证应由后端完成
- 使用 HTTPS 协议传输数据
- 密码字段需使用
type="password"隐藏输入 - 验证码应有有效期限制(后端实现)
完整流程示例
- 用户访问
/forgot-password路由 - 输入注册邮箱后触发验证码发送
- 检查邮箱收到验证码并填写
- 验证通过后跳转至密码重置页面
- 提交新密码后自动跳转至登录页
可通过 Vue Router 配置路由保护,确保重置流程的连贯性。






