验证码实现vue
验证码实现(Vue)
在Vue中实现验证码功能通常需要结合前端生成和验证逻辑,以及可能的后端校验。以下是两种常见实现方式:
基于Canvas的图形验证码
通过Canvas动态生成包含随机字符的图形验证码,适合纯前端场景:
<template>
<div>
<canvas ref="canvas" width="120" height="40" @click="refreshCode"></canvas>
<input v-model="inputCode" placeholder="请输入验证码"/>
<button @click="validate">验证</button>
</div>
</template>
<script>
export default {
data() {
return {
code: '',
inputCode: ''
}
},
mounted() {
this.generateCode()
},
methods: {
generateCode() {
const chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
this.code = ''
for (let i = 0; i < 4; i++) {
this.code += chars.charAt(Math.floor(Math.random() * chars.length))
}
const ctx = this.$refs.canvas.getContext('2d')
ctx.fillStyle = '#f3f3f3'
ctx.fillRect(0, 0, 120, 40)
ctx.font = '20px Arial'
// 绘制干扰线
for (let i = 0; i < 5; i++) {
ctx.strokeStyle = this.randomColor()
ctx.beginPath()
ctx.moveTo(Math.random() * 120, Math.random() * 40)
ctx.lineTo(Math.random() * 120, Math.random() * 40)
ctx.stroke()
}
// 绘制验证码文本
for (let i = 0; i < this.code.length; i++) {
ctx.fillStyle = this.randomColor()
ctx.fillText(this.code[i], 25 * i + 10, 25)
}
},
randomColor() {
return `rgb(${Math.floor(Math.random() * 200)}, ${Math.floor(Math.random() * 200)}, ${Math.floor(Math.random() * 200)})`
},
refreshCode() {
this.generateCode()
},
validate() {
if (this.inputCode.toLowerCase() === this.code.toLowerCase()) {
alert('验证成功')
} else {
alert('验证失败')
this.refreshCode()
}
}
}
}
</script>
结合后端的短信/邮件验证码
需要前后端配合实现时效性验证码,常用于注册/登录场景:
<template>
<div>
<input v-model="phone" placeholder="手机号"/>
<button
:disabled="countdown > 0"
@click="sendCode">
{{ countdown > 0 ? `${countdown}s后重试` : '获取验证码' }}
</button>
<input v-model="inputCode" placeholder="验证码"/>
<button @click="verify">提交</button>
</div>
</template>
<script>
export default {
data() {
return {
phone: '',
inputCode: '',
countdown: 0
}
},
methods: {
sendCode() {
if (!this.phone) return alert('请输入手机号')
// 模拟API请求
this.countdown = 60
const timer = setInterval(() => {
this.countdown--
if (this.countdown <= 0) clearInterval(timer)
}, 1000)
// 实际应调用API接口
// axios.post('/api/send-code', { phone: this.phone })
},
verify() {
// 实际应调用验证接口
// axios.post('/api/verify-code', {
// phone: this.phone,
// code: this.inputCode
// })
alert('验证请求已发送')
}
}
}
</script>
注意事项
- 安全性:纯前端验证码容易被绕过,关键操作需结合后端验证
- 用户体验:图形验证码应提供刷新功能,短信验证码需添加倒计时限制
- 无障碍:为图形验证码提供语音播放替代方案
- 性能:Canvas验证码避免过度复杂的干扰元素影响渲染性能
对于生产环境,推荐使用专业验证码服务如reCAPTCHA或结合后端实现的验证码系统。







