vue实现验证码
Vue 实现验证码的方法
使用 Canvas 生成图形验证码
安装依赖(如需要):
npm install vue-canvas-verify --save
创建验证码组件:
<template>
<div class="captcha">
<canvas ref="canvas" width="120" height="40" @click="refresh"></canvas>
<input v-model="inputCode" placeholder="请输入验证码"/>
</div>
</template>
<script>
export default {
data() {
return {
code: '',
inputCode: ''
}
},
mounted() {
this.drawCode()
},
methods: {
drawCode() {
const ctx = this.$refs.canvas.getContext('2d')
ctx.clearRect(0, 0, 120, 40)
// 生成随机验证码
this.code = Math.random().toString(36).substr(2, 4).toUpperCase()
// 绘制背景
ctx.fillStyle = '#f5f5f5'
ctx.fillRect(0, 0, 120, 40)
// 绘制文字
ctx.font = '24px Arial'
ctx.fillStyle = '#333'
ctx.textAlign = 'center'
ctx.textBaseline = 'middle'
ctx.fillText(this.code, 60, 20)
// 绘制干扰线
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()
}
},
randomColor() {
return `rgb(${Math.floor(Math.random()*256)}, ${Math.floor(Math.random()*256)}, ${Math.floor(Math.random()*256)})`
},
refresh() {
this.drawCode()
this.inputCode = ''
},
validate() {
return this.inputCode.toUpperCase() === this.code
}
}
}
</script>
使用第三方库 vue-verify-code
安装:
npm install vue-verify-code
使用示例:
<template>
<verify-code
:width="120"
:height="40"
@success="handleSuccess"
@error="handleError"
ref="verifyCode"
/>
</template>
<script>
import VerifyCode from 'vue-verify-code'
export default {
components: { VerifyCode },
methods: {
handleSuccess(code) {
console.log('验证成功:', code)
},
handleError() {
console.log('验证失败')
},
refresh() {
this.$refs.verifyCode.refresh()
}
}
}
</script>
短信/邮箱验证码实现
发送验证码按钮组件:
<template>
<button
:disabled="countdown > 0"
@click="sendCode"
>
{{ countdown > 0 ? `${countdown}s后重试` : '获取验证码' }}
</button>
</template>
<script>
export default {
data() {
return {
countdown: 0
}
},
methods: {
sendCode() {
if (this.countdown > 0) return
// 调用API发送验证码
this.$api.sendVerifyCode().then(() => {
this.countdown = 60
const timer = setInterval(() => {
this.countdown--
if (this.countdown <= 0) {
clearInterval(timer)
}
}, 1000)
})
}
}
}
</script>
验证码校验逻辑
在表单提交时验证:
methods: {
submitForm() {
if (!this.validateCode()) {
alert('验证码错误')
return
}
// 提交表单逻辑
},
validateCode() {
// 图形验证码验证
// return this.$refs.captcha.validate()
// 或短信验证码验证
return this.inputCode === this.receivedCode
}
}
安全注意事项
验证码有效期应设置合理时间(通常5分钟) 验证码应区分大小写或统一转换为大写/小写比较 后端必须进行二次验证,前端验证仅用于用户体验 限制单位时间内验证码发送次数,防止短信轰炸 验证码应包含数字和字母组合,避免使用简单模式







