vue实现图片验证
Vue 实现图片验证码
使用 Canvas 生成验证码图片
在 Vue 中可以通过 Canvas 动态生成验证码图片。创建一个组件,利用 Canvas 绘制随机字符和干扰线。
<template>
<div>
<canvas ref="canvas" width="120" height="40" @click="refreshCode"></canvas>
</div>
</template>
<script>
export default {
data() {
return {
code: ''
}
},
mounted() {
this.drawCode()
},
methods: {
drawCode() {
const canvas = this.$refs.canvas
const ctx = canvas.getContext('2d')
ctx.clearRect(0, 0, canvas.width, canvas.height)
// 生成随机验证码
this.code = this.generateRandomCode(4)
// 绘制背景
ctx.fillStyle = this.getRandomColor(180, 240)
ctx.fillRect(0, 0, canvas.width, canvas.height)
// 绘制验证码
for (let i = 0; i < this.code.length; i++) {
ctx.font = '20px Arial'
ctx.fillStyle = this.getRandomColor(50, 160)
ctx.fillText(this.code[i], 20 + i * 20, 25)
}
// 绘制干扰线
for (let i = 0; i < 5; i++) {
ctx.strokeStyle = this.getRandomColor(40, 180)
ctx.beginPath()
ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height)
ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height)
ctx.stroke()
}
},
generateRandomCode(length) {
const chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
let result = ''
for (let i = 0; i < length; i++) {
result += chars.charAt(Math.floor(Math.random() * chars.length))
}
return result
},
getRandomColor(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()
}
}
}
</script>
服务器端验证
前端生成验证码后,需要将验证码值发送到服务器进行存储,通常存储在 session 中。当用户提交表单时,将用户输入的验证码与服务器存储的值进行比对。
// 在提交表单时验证
methods: {
submitForm() {
if (this.userInputCode !== this.code) {
alert('验证码错误')
this.refreshCode()
return
}
// 继续表单提交逻辑
}
}
使用第三方库
可以使用现成的 Vue 验证码组件,如 vue-captcha 或 vue-img-verify,简化开发流程。
安装 vue-captcha:
npm install vue-captcha --save
使用示例:
<template>
<vue-captcha ref="captcha" @verify="onVerify"></vue-captcha>
</template>
<script>
import VueCaptcha from 'vue-captcha'
export default {
components: { VueCaptcha },
methods: {
onVerify(response) {
if (response) {
// 验证通过
}
}
}
}
</script>
安全注意事项
验证码应该有一定时效性,通常在服务器端设置过期时间。避免使用纯数字验证码,增加破解难度。可以考虑加入简单的算术验证码提高安全性。
前端生成的验证码需要配合服务器端验证,不能仅依赖前端验证。验证码图片应该定期刷新,防止暴力破解。







