vue实现验证码
Vue 实现验证码的方法
使用组件库实现
许多现成的 Vue 组件库提供了验证码功能,例如 Element UI 或 Vant。这些组件通常包含图形验证码或短信验证码的实现方式。
安装 Element UI:
npm install element-ui -S
在 Vue 中使用 Element UI 的验证码组件:

<template>
<el-form>
<el-form-item label="验证码">
<el-input v-model="captcha" placeholder="请输入验证码"></el-input>
<el-button @click="refreshCaptcha">刷新验证码</el-button>
</el-form-item>
<img :src="captchaImage" @click="refreshCaptcha" alt="验证码">
</el-form>
</template>
<script>
export default {
data() {
return {
captcha: '',
captchaImage: ''
}
},
methods: {
refreshCaptcha() {
this.captchaImage = `/api/captcha?t=${Date.now()}`
}
},
mounted() {
this.refreshCaptcha()
}
}
</script>
自定义图形验证码
如果需要完全自定义验证码,可以使用 Canvas 绘制验证码图形。
创建验证码组件:

<template>
<div class="captcha-container">
<canvas ref="canvas" width="120" height="40" @click="generateCaptcha"></canvas>
<input type="text" v-model="inputCaptcha" placeholder="请输入验证码">
</div>
</template>
<script>
export default {
data() {
return {
captchaText: '',
inputCaptcha: ''
}
},
methods: {
generateCaptcha() {
const canvas = this.$refs.canvas
const ctx = canvas.getContext('2d')
ctx.clearRect(0, 0, canvas.width, canvas.height)
this.captchaText = Math.random().toString(36).substr(2, 6).toUpperCase()
ctx.fillStyle = '#f3f3f3'
ctx.fillRect(0, 0, canvas.width, canvas.height)
ctx.font = '24px Arial'
ctx.fillStyle = '#333'
ctx.fillText(this.captchaText, 10, 30)
// 添加干扰线
for (let i = 0; i < 5; i++) {
ctx.strokeStyle = `rgb(${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)})`
ctx.beginPath()
ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height)
ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height)
ctx.stroke()
}
},
validateCaptcha() {
return this.inputCaptcha.toUpperCase() === this.captchaText
}
},
mounted() {
this.generateCaptcha()
}
}
</script>
短信验证码实现
短信验证码通常需要后端支持,前端主要负责倒计时和重发逻辑。
短信验证码组件示例:
<template>
<div class="sms-code">
<input v-model="smsCode" placeholder="请输入短信验证码">
<button :disabled="countdown > 0" @click="sendSmsCode">
{{ countdown > 0 ? `${countdown}秒后重试` : '获取验证码' }}
</button>
</div>
</template>
<script>
export default {
data() {
return {
smsCode: '',
countdown: 0,
timer: null
}
},
methods: {
sendSmsCode() {
// 调用API发送短信
this.$axios.post('/api/send-sms', { phone: this.phone })
.then(() => {
this.startCountdown()
})
},
startCountdown() {
this.countdown = 60
this.timer = setInterval(() => {
this.countdown--
if (this.countdown <= 0) {
clearInterval(this.timer)
}
}, 1000)
}
},
beforeDestroy() {
clearInterval(this.timer)
}
}
</script>
验证码校验逻辑
无论使用哪种验证码,都需要在后端进行校验。前端可以预先进行简单验证:
validateForm() {
if (!this.validateCaptcha()) {
this.$message.error('验证码错误')
return false
}
// 其他表单验证...
return true
}
安全注意事项
- 图形验证码应在服务端生成并校验,前端仅负责显示
- 短信验证码应有频率限制,防止恶意刷短信
- 验证码应有有效期限制
- 重要操作应使用更安全的验证方式,如二次验证
以上方法提供了在 Vue 中实现验证码的多种方案,可根据实际需求选择合适的实现方式。






