验证码实现vue
验证码实现(Vue.js)
使用纯前端生成图形验证码
安装 vaptcha 或 vue-captcha 等专用库:
npm install vue-captcha --save
组件引入示例:
<template>
<vue-captcha
:length="4"
@change="onCaptchaChange"
/>
</template>
<script>
import VueCaptcha from 'vue-captcha'
export default {
components: { VueCaptcha },
methods: {
onCaptchaChange(code) {
console.log('验证码:', code)
}
}
}
</script>
结合Canvas绘制验证码
创建独立组件Captcha.vue:
<template>
<canvas
ref="canvas"
@click="refreshCode"
width="120"
height="40"
/>
</template>
<script>
export default {
data() {
return {
code: ''
}
},
mounted() {
this.drawCode()
},
methods: {
generateCode() {
const chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
this.code = Array.from({length:4},
() => chars[Math.floor(Math.random()*chars.length)]
).join('')
},
drawCode() {
const ctx = this.$refs.canvas.getContext('2d')
ctx.fillStyle = this.randomColor(180, 240)
ctx.fillRect(0, 0, 120, 40)
// 绘制干扰线
for(let i=0; i<5; i++) {
ctx.strokeStyle = this.randomColor(40, 180)
ctx.beginPath()
ctx.moveTo(
Math.random()*120,
Math.random()*40
)
ctx.lineTo(
Math.random()*120,
Math.random()*40
)
ctx.stroke()
}
// 绘制验证码文本
this.generateCode()
ctx.font = '26px Arial'
ctx.textAlign = 'center'
for(let i=0; i<this.code.length; i++) {
ctx.fillStyle = this.randomColor(0, 100)
ctx.fillText(
this.code[i],
30*(i+0.6),
28
)
}
},
randomColor(min, max) {
const r = min + Math.floor(Math.random()*(max-min))
const g = min + Math.floor(Math.random()*(max-min))
const b = min + Math.floor(Math.random()*(max-min))
return `rgb(${r},${g},${b})`
},
refreshCode() {
this.drawCode()
this.$emit('update:code', this.code)
}
}
}
</script>
服务端验证方案
前端调用示例:
async submitForm() {
const isValid = await this.$refs.captcha.validate(inputCode)
if(!isValid) {
alert('验证码错误')
return
}
// 继续提交表单
}
后端Node.js验证逻辑示例:
app.post('/verify', (req, res) => {
const { inputCode, sessionCode } = req.body
if(inputCode.toLowerCase() === sessionCode.toLowerCase()) {
res.json({ valid: true })
} else {
res.json({ valid: false })
}
})
滑动验证码集成
使用第三方服务如极验:
<template>
<div id="geetest-captcha"></div>
</template>
<script>
export default {
mounted() {
initGeetest({
gt: "YOUR_GT_KEY",
challenge: "SERVER_GENERATED_CHALLENGE",
offline: false
}, (captchaObj) => {
captchaObj.appendTo("#geetest-captcha")
captchaObj.onSuccess(() => {
const result = captchaObj.getValidate()
this.$emit('verified', result)
})
})
}
}
</script>
注意事项
- 生产环境建议使用专业验证码服务(如reCAPTCHA、极验)
- 前端生成的验证码需配合服务端会话存储验证
- 定期更新验证码生成算法防止破解
- 移动端需考虑触控交互体验







