在 Vue3 项目中实现图形验证码功能,有以下几种优秀的解决方案:
npm install vue3-verify-code
示例:
<template>
<verify-code @success="handleSuccess" />
</template>
<script setup>
import { VerifyCode } from 'vue3-verify-code'
const handleSuccess = () => {
console.log('验证通过')
}
</script>
npm install vue-captcha --save
示例代码:
<template>
<canvas ref="canvas" @click="refreshCode"></canvas>
<input v-model="inputCode" />
</template>
<script setup>
import { ref, onMounted } from 'vue'
const canvas = ref(null)
const inputCode = ref('')
const correctCode = ref('')
onMounted(() => {
refreshCode()
})
const refreshCode = () => {
const ctx = canvas.value.getContext('2d')
// 生成随机验证码并绘制
correctCode.value = generateRandomCode()
drawCode(ctx, correctCode.value)
}
// 验证函数
const validate = () => {
return inputCode.value.toLowerCase() === correctCode.value.toLowerCase()
}
</script>
npm install vue3-recaptcha2
示例:
<template>
<vue-recaptcha
sitekey="your_site_key"
@verify="onVerify"
@expired="onExpired"
/>
</template>
<script setup>
import { VueRecaptcha } from 'vue3-recaptcha2'
const onVerify = (response) => {
console.log('验证通过:', response)
}
const onExpired = () => {
console.log('验证过期')
}
</script>
svg-captcha
或 trek-captcha
生成示例后端代码 (Node.js):
const svgCaptcha = require('svg-captcha')
app.get('/captcha', (req, res) => {
const captcha = svgCaptcha.create()
req.session.captcha = captcha.text // 存储到session
res.type('svg')
res.status(200).send(captcha.data)
})
前端调用:
const refreshCaptcha = async () => {
const response = await fetch('/captcha')
captchaImage.value = await response.text()
}
您可以根据项目具体需求选择合适的验证码方案。需要更详细的实现指导或针对特定方案的代码示例吗?