vue实现忘记密码
Vue 实现忘记密码功能
忘记密码功能通常包括以下步骤:用户输入邮箱或手机号,系统发送验证码或重置链接,用户验证后设置新密码。以下是基于 Vue 的实现方法。
前端页面设计
创建一个忘记密码的表单页面,包含邮箱或手机号输入框、验证码输入框和提交按钮。使用 Vue 的双向绑定功能实现数据同步。

<template>
<div class="forgot-password">
<h3>忘记密码</h3>
<form @submit.prevent="handleSubmit">
<div class="form-group">
<label for="email">邮箱</label>
<input
type="email"
id="email"
v-model="form.email"
placeholder="请输入注册邮箱"
required
/>
</div>
<div class="form-group">
<label for="code">验证码</label>
<input
type="text"
id="code"
v-model="form.code"
placeholder="请输入验证码"
required
/>
<button
type="button"
@click="sendCode"
:disabled="isSending"
>
{{ isSending ? `${countdown}s后重新发送` : '发送验证码' }}
</button>
</div>
<button type="submit">提交</button>
</form>
</div>
</template>
发送验证码逻辑
实现发送验证码的功能,包括倒计时和防重复发送。

<script>
export default {
data() {
return {
form: {
email: '',
code: '',
},
isSending: false,
countdown: 60,
};
},
methods: {
sendCode() {
if (this.isSending) return;
this.isSending = true;
// 调用API发送验证码
this.$axios.post('/api/send-code', { email: this.form.email })
.then(() => {
const timer = setInterval(() => {
this.countdown--;
if (this.countdown <= 0) {
clearInterval(timer);
this.isSending = false;
this.countdown = 60;
}
}, 1000);
})
.catch(() => {
this.isSending = false;
});
},
handleSubmit() {
// 验证表单数据
if (!this.form.email || !this.form.code) {
alert('请填写完整信息');
return;
}
// 调用API验证验证码并重置密码
this.$axios.post('/api/reset-password', this.form)
.then(() => {
alert('密码重置成功,请登录');
this.$router.push('/login');
})
.catch(error => {
alert(error.response.data.message);
});
},
},
};
</script>
后端接口设计
后端需要提供两个接口:发送验证码和重置密码。发送验证码接口生成验证码并发送到用户邮箱,重置密码接口验证验证码并更新密码。
// 发送验证码接口示例
router.post('/api/send-code', async (req, res) => {
const { email } = req.body;
const code = Math.floor(1000 + Math.random() * 9000).toString();
// 存储验证码,可以使用Redis或数据库
await saveCode(email, code);
// 发送邮件
await sendEmail(email, '验证码', `您的验证码是:${code}`);
res.json({ success: true });
});
// 重置密码接口示例
router.post('/api/reset-password', async (req, res) => {
const { email, code, password } = req.body;
// 验证验证码
const savedCode = await getCode(email);
if (savedCode !== code) {
return res.status(400).json({ message: '验证码错误' });
}
// 更新密码
await updatePassword(email, password);
res.json({ success: true });
});
安全性考虑
- 验证码有效期:设置验证码的有效期,通常为5-10分钟。
- 防暴力破解:限制验证码尝试次数,防止暴力破解。
- HTTPS:确保所有通信通过HTTPS加密,防止中间人攻击。
样式优化
使用CSS或UI框架(如Element UI、Vuetify)美化表单,提升用户体验。
<style scoped>
.forgot-password {
max-width: 400px;
margin: 0 auto;
padding: 20px;
}
.form-group {
margin-bottom: 15px;
}
input {
width: 100%;
padding: 8px;
margin-top: 5px;
}
button {
padding: 8px 15px;
background: #42b983;
color: white;
border: none;
cursor: pointer;
}
button:disabled {
background: #ccc;
}
</style>
通过以上步骤,可以实现一个完整的忘记密码功能,涵盖前端页面、交互逻辑和后端接口。






