vue实现找回密码源码
以下是一个基于Vue.js的找回密码功能实现方案,包含前后端交互逻辑和关键代码示例:

核心功能实现
前端部分(Vue.js)

<template>
<div class="forgot-password">
<form @submit.prevent="handleSubmit">
<input v-model="email" type="email" placeholder="注册邮箱" required>
<button type="submit">发送验证码</button>
</form>
<div v-if="showResetForm">
<input v-model="code" placeholder="验证码">
<input v-model="newPassword" type="password" placeholder="新密码">
<button @click="resetPassword">重置密码</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
email: '',
code: '',
newPassword: '',
showResetForm: false
}
},
methods: {
async handleSubmit() {
try {
await this.$http.post('/api/auth/forgot-password', { email: this.email })
this.showResetForm = true
this.$message.success('验证码已发送至邮箱')
} catch (error) {
console.error(error)
}
},
async resetPassword() {
try {
await this.$http.post('/api/auth/reset-password', {
email: this.email,
code: this.code,
newPassword: this.newPassword
})
this.$message.success('密码重置成功')
this.$router.push('/login')
} catch (error) {
console.error(error)
}
}
}
}
</script>
后端接口示例(Node.js)
// 发送验证码接口
router.post('/forgot-password', async (req, res) => {
const { email } = req.body
const user = await User.findOne({ email })
if (!user) {
return res.status(404).json({ message: '用户不存在' })
}
const code = Math.random().toString(36).substr(2, 6)
await sendEmail(email, '密码重置验证码', `您的验证码是: ${code}`)
// 存储验证码到数据库或缓存
await VerificationCode.create({ email, code })
res.json({ success: true })
})
// 重置密码接口
router.post('/reset-password', async (req, res) => {
const { email, code, newPassword } = req.body
const record = await VerificationCode.findOne({
email,
code,
createdAt: { $gt: new Date(Date.now() - 30 * 60 * 1000) } // 30分钟内有效
})
if (!record) {
return res.status(400).json({ message: '验证码无效或已过期' })
}
const user = await User.findOne({ email })
user.password = await bcrypt.hash(newPassword, 10)
await user.save()
// 清除已使用的验证码
await VerificationCode.deleteMany({ email })
res.json({ success: true })
})
安全注意事项
密码重置令牌应当设置有效期(通常30分钟) 验证码应当一次性使用,重置后立即失效 新密码应当符合复杂度要求并加密存储 前端应对输入进行基本验证(非空、邮箱格式等)
扩展功能建议
添加图形验证码防止暴力请求 实现密码强度实时检测 增加密码重置链接方式(邮件链接跳转) 记录密码重置日志用于安全审计
以上代码示例展示了Vue实现密码找回功能的核心流程,实际应用中需要根据具体框架和技术栈进行调整。前端部分使用Vue的单文件组件格式,后端示例使用Node.js+Express,数据库操作部分需要根据实际ORM进行调整。






